Continue to Site

Welcome to EDAboard.com

Welcome to our site! EDAboard.com is an international Electronics Discussion Forum focused on EDA software, circuits, schematics, books, theory, papers, asic, pld, 8051, DSP, Network, RF, Analog Design, PCB, Service Manuals... and a whole lot more! To participate you need to register. Registration is free. Click here to register now.

Converting from binary to hexadecimal using C18

Status
Not open for further replies.

Anthony_87

Newbie level 4
Joined
Feb 25, 2010
Messages
6
Helped
0
Reputation
0
Reaction score
0
Trophy points
1,281
Activity points
1,330
Dear all,

I need help in converting an unsigned char array[8] (that actually contains the binary bits) and convert it to a hexadecimal notation!!
for example I have something like that:
unsigned char data[8] = {0,0,1,1,0,0,1,1}
and i need a function to return the converted value 0x33

so is there any function in the C18 library that do the trick? if not, can someone help me with the code?

Thanks in advance
Best Regards
 

Actually, I don't know is there such as function, but it is not a problem to write it yourself.

For example, your a number in binary is {0,0,1,1,0,0,1,1}.
In hex there is two chars 0-F. So that, you need to divide yur binary number into two parts: 0011 and 0011. Then, as you can see, there's only 16 possible variants of each part. You can convert from binary to hex using this table:
binary hex
0000 0
0001 1
0010 2
0011 3
...... ..
1010 A
1011 B
....... ..


Then just join two parts.
 

anyone can easily do a switch case algorithm, but thats not the right method, lets say u have to convert a 16bit word to hex ... it just wont work !! I need to a general algorithm :/
 

I dont have any of my pascal source code available, but...

1) build an array CH of '0123456789ABCDF'
2) use two temp variables to hold 'high' and 'low' nybbles.
3) use two temp char variables to hold the two CH(high) and CH(low) chars.
return the 2-char value.

Easily modifiable for 16-bits...

Hope that helps!

Edit: Here is one for 16-bit values that is a bit more 'elaborate'...

MODULE DHCV;
VAR
AH : EXTERNAL STRING;
A : EXTERNAL INTEGER;
D : EXTERNAL REAL;

PROCEDURE DHCV;
VAR
X,Y : INTEGER;
X1,X2,X3,X4 : INTEGER;
Y1,Y2,Y3,Y4 : INTEGER;
N : STRING;
BEGIN
N := '0123456789ABCDEF';
Y := trunc(D);
Y1 := shr((Y & $F000),12);
Y2 := shr((Y & $0F00),8);
Y3 := shr((Y & $00F0),4);
Y4 := (Y & $000F);

AH := CONCAT(N[y1+1],N[y2+1],N[Y3+1],N[Y4+1]);
d := d + 1;
end;
 

something like this will work:

unsigned char i, x = 0;

for(i=0;i<8;i++)
{
x = x<<1;
if( data==1 )
x = x | 1;

}

here x will have the value formed by the binary digits.
 

Status
Not open for further replies.

Similar threads

Part and Inventory Search

Welcome to EDABoard.com

Sponsor

Back
Top