Friday, April 25, 2008

ASCII to Hex in Verilog

I was playing around with Verilog today, it was one of those whimsical things that one does to take ones mind off writing a dissertation :) I tried it for the first time, and I like it, it seems fairly easy to pick up too. Here is a function I wrote to convert an ascii number to its ascii-hexadecimal equivalent -

/**

* converts an 8-bit wide parameter to a 16-bit wide ascii-hexadecimal equivalent
* @return 16-bit ascii-hexadecimal version of input
**/
function [15:0] a2h(i) //the function returns a 16-bit value
input [7:0] i; //input argument 8-bit wide
reg [4:0] temp;
reg [7:0] h_b, l_b;
begin
temp = i[7:4];
h_b = decode(temp); //decode higher nibble
temp = i[3:0];
l_b = decode(temp); //decode lower nibble
a2h = {h_b, l_b}; //concatenate the higher nibble result and lower nibble result
end
endfunction

/**
* Helper function to convert from nibble to ASCII representation
*/
function [7:0] decode(d_i) //output is byte wide
input [3:0] d_i; //input is nibble wide
reg [7:0] ret_value;
reg [2:0] lo_ip;
begin //this is the conversion logic... will not explain this :P
ret_value = 8'd00;
ret_value[2:0] = d_i[2:0];
if(d_i == 4'h9){
ret_value[3] = 1b'1;
}
if(d_i > 4'h9){
ret_value[7:4] = 4h'4;
}else{
ret_value[7:4] = 4h'3;
}
decode = ret_value;
end
endfunction

"a2h" accepts an input 8-bits wide and converts it to a 16-bit ascii representation of that input.

i.e. 'b' would get converted to '62'
and '6' would get converted to '36'.

No comments: