## Bit slicing in verilog - programming-languages

How can I write wdata[((8*j)+7) : (8*i)] = $random; in verilog programming language? , where i and j are reg type variable. Modelsim gives error for constant range variable. How could I write it in proper manner.

You should think from Hardware prospective for the solution.
Here is one solution. Hope that it will help you.
module temp(clk);
input clk;
reg i, j;
reg [23:0] register, select;
wire [23:0] temp;
initial
begin
i = 'd1;
j = 'd1;
end
generate
for(genvar i = 0; i<24; i++)
begin
assign temp[i] = select[i] ? $random : register[i];
end
endgenerate
always # (posedge clk)
begin
register <= temp;
end
always # *
begin
select = (32'hffff_ffff << ((j<<3)+8)) ^ (32'hffff_ffff << (i<<3));
end
endmodule

Use the array slicing construction. You can find more detailed explanation at Array slicing Q&A
bit [7:0] PA, PB;
int loc;
initial begin
loc = 3;
PA = PB; // Read/Write
PA[7:4] = 'hA; // Read/Write of a slice
PA[loc -:4] = PA[loc+1 +:4]; // Read/Write of a variable slice equivalent to PA[3:0] = PA[7:4];
end
Verilog 2001 Syntax
[M -: N] // negative offset from bit index M, N bit result
[M +: N] // positive offset from bit index M, N bit result

## Related

### function which gets another function as argument in SML

Consider function g gets integer and returns true if the integer is bigger than some random const positive value that was decided before, otherwise false. I would like to write a function f in SML which gets the function g as argument. this function f should return this random const positive value that was decided before. Algorithm (In some other language, C or something): int f(int num) { int num = 1; while(!g(num)) { num++; } return num; } Now this is what I tried in SML: fun f g = let val num = 1; in while !(g num) do ( val num = num + 1; ); num end; But it doesn't work. Any suggestions?

val num = num + 1; First of all val is only allowed at the top level or inside a let. Secondly it defines a new variable. So in your C code, it'd be equivalent to: int num = num + 1; And not: num = num + 1; In other words, it creates a new variable rather than modifying the existing one, which doesn't help you here. So the natural follow-up question would be how you do num = num + 1. And the most direct answer is: you don't. All variables in SML are immutable, so you can't re-assign variables. However you can work around this by using refs, which are mutable. However the proper way to do this in SML is to not use while loops or re-assignments at all and instead use recursion.

As sepp2k explained, your problem has nothing to do with the passing of g but how you try to define a loop. Here is one way to implement it using recursion, which is what you normally do in ML: fun f' g n = if g n then n else f' g (n + 1) fun f g = f' g 1 Or if you want to keep the auxiliary function local: fun f g = let fun loop n = if g n then n else loop (n + 1) in loop 1 end

### systemVerilog - How can I convert int unsigned to array logic?

I have the following : logic [15:0] tb_real_din, tb_image_din; int unsigned counter; //write proc initial begin tb_last_dvalid = 1'b0; tb_we = 1'b0; #80ns; for (int i = 0 ; i <= 32; i++) begin counter = counter+1; tb_real = counter; tb_image = counter; if (i == 32) tb_last_dvalid = 1'b1; #8ns; tb_we = 1'b1; #8ns; tb_we = 1'b0; tb_last_dvalid = 1'b0; end end // initial begin I got the following error: Illegal reference to net "tb_real". How can I convert int unsigned to array logic?

Your problem is nothing to do with converting between types. Your problem is probably because you have not declared tb_real. Anything undeclared in System-verilog defaults to being a 1-bit wire; a wire is a kind of net and it is illegal to assign to nets from initial, always or final blocks. Hence, your error message. I say "probably" because you have not give an MCVE.

### Pascal to C# conversion

I am trying to convert this pascal code into C# in order to communicate with a peripheral device attached to a comm port. This piece of code should calculate the Control Byte, however I'm not getting the right hex Value therefore I'm wondering if I'm converting the code in the right way. Pascal: begin check := 255; for i:= 3 to length(sequence)-4 do check := check xor byte(sequence[i]); end; C#: int check = 255; for (int x = 3; x < (sequence.Length - 4); x++) { check = check ^ (byte)(sequence[x]); } Pascal function: { *** conversion of number into string ‘hex’ *** } function word_to_hex (w: word) : string; var i : integer; s : string; b : byte; c : char; begin s := ‘’; for i:= 0 to 3 do begin b := (hi(w) shr 4) and 15; case b of 0..9 : c := char(b+$30); 10..15 : c := char(b+$41-10); end; s := s + c; w := w shl 4; end; word_ to_hex := s; end; C# Equivalent: public string ControlByte(string check) { string s = ""; byte b; char c = '\0'; //shift = check >> 4 & 15; for (int x = 0; x <= 3; x++) { b = (byte)((Convert.ToInt32(check) >> 4) & 15); if (b >= 0 && b <= 9) { c = (char)(b + 0x30); } else if (b >= 10 && b <= 15) { c = (char)(b + 0x41 - 10); } s = s + c; check = (Convert.ToInt32(check) << 4).ToString(); } return s; } And last pascal: function byte_to_hex (b:byte) : string; begin byte_to_hex := copy(word_to_hex(word(b)),3,2); end; which i am not sure how is substringing the result from the function. So please let me know if there is something wrong with the code conversion and whether I need to convert the function result into bytes. I appreciate your help, UF. Further info EDIT: Initially I send a string sequence containing the command and information that printer is supposed to print. Since every sequence has a unique Control Byte (in Hex) I have to calculate this from the sequence (sequence = "P1;1$l201PrinterPrinterPrinter1B/100.00/100.00/0/\") which is what upper code does according to POSNET=>"cc – control byte, encoded as 2 HEX digits (EXOR of all characters after ESC P to this byte with #255 initial quantity), according to the following algorithm in PASCAL language:(see first code block)".=>1. check number calculated in the above loop which constitutes control byte should be recoded into two HEX characters (ASCII characters from scope: ‘0’..’9’,’A’..’F’,’a’..’f’), utilizing the following byte_to_hex function:(see third code block). =>{* conversion of byte into 2 characters *}(see 5th code block)

The most obvious problem that I can see is that the Pascal code operates on 1-based 8 bit encoded strings, and the C# code operates on 0-based 16 bit encoded strings. To convert the Pascal/Delphi code that you use to C# you need to address the mis-match. Perhaps like this: byte[] bytes = Encoding.Default.GetBytes(sequence); int check = 255; for (int i = 2; i < bytes.Length-4; i++) { check ^= bytes[i]; } Now, in order to write this I've had to make quite a few assumptions, because you did not include anywhere near enough code in the question. Here's what I assumed: The Pascal sequence variable is a 1-based 8 bit ANSI encoded Delphi AnsiString. The Pascal check variable is a Delphi 32 bit signed Integer. The C# sequence variable is a C# string. If any of those assumptions prove to be false, then the code above will be no good. For instance, perhaps the Pascal check is really Byte. In which case I guess the C# code should be: byte[] bytes = Encoding.Default.GetBytes(sequence); byte check = 255; for (int i = 2; i < bytes.Length - 4; i++) { check ^= bytes[i]; } I hope that this persuades you of the importance of supplying complete information. That's really all the meat of this question. The rest of the code concerns converting values to hex strings in C# code. That has been covered again and again here on Stack Overflow. For instance: C# convert integer to hex and back again How do you convert Byte Array to Hexadecimal String, and vice versa? There are many many more such questions.

### Is there a way to search SQL database for similar words (mean not identical words)?

Is there a way to search MySQL database for similar words (mean not identical words) . For example : user searches in database for word "abcd" and there is a word "abd" in the database so the search engine or the program Ask the user "Do you mean [abd] ? " as in most of search engines in the web ? Please notice that the search word is not a part of the existing word (can't use "like")

Have a look at the Damerau-Levenshtein distance algorithm. It calculates the "distance" between two strings and determines how many steps it takes to transform one string into another. The less steps the closer the two strings are. This article shows the algorithm implemented as a MySQL stored function. The algorithm is so much better than LIKE or SOUNDEX. I believe Google uses crowd sourced data rather than an algorithm. ie if a user types in abcd, clicks on the back button and then immediately searches for abd then it establishes a relationship between the two search terms as the user wasn't happy with the results. Once you have a very large community searching then the pattern appears.

Depends on how far apart they are, you could look into soundex perhaps.. http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_soundex

Check out Levenshtein_distance

Another technique is to create indexes on trigrams.

Since the link in Dave Barker's answer is dead, here is the code from an archived version of the website: CREATE FUNCTION LEVENSHTEIN (s1 VARCHAR(255), s2 VARCHAR(255)) RETURNS INT DETERMINISTIC BEGIN DECLARE s1_len, s2_len, i, j, c, c_temp, cost INT; DECLARE s1_char CHAR; DECLARE cv0, cv1 VARBINARY(256); SET s1_len = CHAR_LENGTH(s1), s2_len = CHAR_LENGTH(s2), cv1 = 0x00, j = 1, i = 1, c = 0; IF s1 = s2 THEN RETURN 0; ELSEIF s1_len = 0 THEN RETURN s2_len; ELSEIF s2_len = 0 THEN RETURN s1_len; ELSE WHILE j <= s2_len DO SET cv1 = CONCAT(cv1, UNHEX(HEX(j))), j = j + 1; END WHILE; WHILE i <= s1_len DO SET s1_char = SUBSTRING(s1, i, 1), c = i, cv0 = UNHEX(HEX(i)), j = 1; WHILE j <= s2_len DO SET c = c + 1; IF s1_char = SUBSTRING(s2, j, 1) THEN SET cost = 0; ELSE SET cost = 1; END IF; SET c_temp = CONV(HEX(SUBSTRING(cv1, j, 1)), 16, 10) + cost; IF c > c_temp THEN SET c = c_temp; END IF; SET c_temp = CONV(HEX(SUBSTRING(cv1, j+1, 1)), 16, 10) + 1; IF c > c_temp THEN SET c = c_temp; END IF; SET cv0 = CONCAT(cv0, UNHEX(HEX(c))), j = j + 1; END WHILE; SET cv1 = cv0, i = i + 1; END WHILE; END IF; RETURN c; END To note: Maximum length of input strings is 255 characters. I’m sure you could edit the function to support more if needed. I’ve tested it with international characters on a utf8_bin column and it seemed to work, but I’ve not tested that capability exstensively. I’ve only tested it on MySQL 5.0+. No idea how it will work on versions less than that. And as a bonus I also created a helper function that returns the ratio (as a percentage) of different : same characters which can be more helpful than just a straight edit distance (idea from here). CREATE FUNCTION LEVENSHTEIN_RATIO (s1 VARCHAR(255), s2 VARCHAR(255)) RETURNS INT DETERMINISTIC BEGIN DECLARE s1_len, s2_len, max_len INT; SET s1_len = LENGTH(s1), s2_len = LENGTH(s2); IF s1_len > s2_len THEN SET max_len = s1_len; ELSE SET max_len = s2_len; END IF; RETURN ROUND((1 - LEVENSHTEIN(s1, s2) / max_len) * 100); END

### Fortran Function explanation

I have this function in Fortran and i'm trying to recode it in C# C **************************************************************** C FUNCTION POLY C***************************************************************** FUNCTION POLY(N,A,X) DIMENSION A(N) C POLY = 0. L = N DO 1 K = 1,N POLY = POLY*X + A(L) 1 L = L-1 RETURN END C***************************************************************** I found out that DIMENSION A(N) creates a vector of N values, but we already have a variable A from the function parameters, does this means that the array values all equal to A? If so then what is the use of A(N). By the way can anyone just explain what does this function do so i can re-implement it in C#

FUNCTION POLY(N,A,X) ! implicitly real (float) function poly(int n,int a,real x) DIMENSION A(N) ! shape A as 1d array of n values in this scope C ! say nothing (blank comment) POLY = 0. ! initialise return variable to float value 0 L = N ! set L (implicitly integer) to n DO 1 K = 1,N ! for(int k=1; k<=n; ++k) POLY = POLY*X + A(L) ! update return variable 1 L = L-1 ! decrement L RETURN ! return current value for poly END so in c-like syntax: float poly(int n, int a, float x) { // redim a(n) float result = 0; int l = n; for(int k=1; k <= n; ++k) { result = result*x + a(l); --l; } return result; } The bit that doesn't translate is redimensioning A as an array. In C you would pass a pointer and use it as an array, and in C++/C# you'd probably pass a vector-like structure with its own length property. In C#, using a list: float poly(List<float> coeffs, float x) { float result = 0; for(int i=coeffs.Count-1; i >= 0; --i) { result = result*x + coeff[i]; } return result; }

It evaluates a polynomial in x of the form: a[1] + a[2]x + a[3]x^2 + ... a[N]x^(N-1) Remember that Fortran uses 1-based array indices and I have followed that convention in this equation. You could write it in C# like this: double EvaluatePolynomial(double[] a, double x) { double result = 0.0; int i = a.Length; while (i>0) { i--; result = result*x + a[i]; } return result; } Here we are using 0-based array indexing appropriate to C#. And so this function evalutates a polynomial in x of the form: a[0] + a[1]x + a[2]x^2 + ... a[N-1]x^(N-1)

guessing slightly I think this is specifying that the parameter A itself is an array of N elements. So for the C# equivalent you wouldn't need a separate N parameter; you would only need to pass A as a double[], as in .NET arrays can tell you their .Length. The function evaluates polynomials using Horner's method.

The line DIMENSION A(N) just declares details of the A dummy argument (PARAMETERs are something very different in Fortran), i.e. it says it is an array from 1 to N. The other ones are not declared this way, because the function uses implicit typing.