convert hex to bcd in c

Status
Not open for further replies.

erodeboy

Member level 5
Joined
Nov 15, 2005
Messages
80
Helped
3
Reputation
6
Reaction score
2
Trophy points
1,288
Location
India
Activity points
1,987
hex to bcd

how to convert a hex value to bcd using keil c
 

hex to bcd conversion in c

Salam,

You didn't mention what is the length of the hex 8 bit, 16 bits ...etc

Ok here is a simple method to convert hex (8bit) to bcd

One restriction that method is vaild fot numbers 0 - 99 only.

for example if you want to convert 99 to bcd

1- divide 99 by 10
2- put the result in the high nibble of the result variable
3- put the reminder in the low nibble of the result variable

This method is very easy to implement in C like this

Code:
unsigned char hex2bcd (unsigned char x)
{
    unsigned char y;
    y = (x / 10) << 4;
    y = y | (x % 10);
    return (y);
}
Where X is the Hex , and Y is the result

Enjoy

Bye
 

    erodeboy

    Points: 2
    Helpful Answer Positive Rating
hex to bcd conversion c code


https://www.boerde.de/~matthias/m8051/bin2bcd.zip
 

hex to bcd in c

float a;
unsigned char b;


b = 0xff;
a = b;
 

Re: convert bcd to hex in c

// pass input 8 bit BCD format and conversion length, and get back hex values
// in output buffer.
void Bcd_To_Hex(unsigned char *Input_Buff, unsigned char *Output_Buff,unsigned char Len)
{ // by Neeraj Verma : neeraj.niet@gmail.com
unsigned char i,j;
for(i=0,j=0;i<Len;i++,j++)
{ if((i+1) >= Len)
{
if(*(Input_Buff+Len-1-i) >0x40)
*(Output_Buff+j) = (*(Input_Buff+Len-1-i)-0x37);
else
*(Output_Buff+j) = (*(Input_Buff+Len-1-i)-0x30);
}
else
{
if(*(Input_Buff+Len-1-i) >0x40)
{ if(*(Input_Buff+Len-2-i) >0x40)
{
*(Output_Buff+j) = ((*(Input_Buff+Len-i-2)-0x37)<<4) | (*(Input_Buff+Len-1-i)-0x37);
}
else
{
*(Output_Buff+j) = ((*(Input_Buff+Len-i-2)-0x30)<<4) | (*(Input_Buff+Len-1-i)-0x37);
}
}
else
{ if(*(Input_Buff+Len-2-i) >0x40)
{
*(Output_Buff+j) = ((*(Input_Buff+Len-i-2)-0x37)<<4) | (*(Input_Buff+Len-1-i)-0x30);
}
else
{
*(Output_Buff+j) = ((*(Input_Buff+Len-i-2)-0x30)<<4) | (*(Input_Buff+Len-1-i)-0x30);
}
}
}
i++;
}
}
 

/* Prototype */
void Hex2Decimal(unsigned long num);

/* Hex Variable in any register */
unsigned long num = 0x499602D2 ; /* 1234567890 */

int main (void)
{
Hex2Decimal(num); /* Convert given hex to decimal digits */

return 1; /* Good C!, not required */
}

/* Function */

/* Converts an unsigned hex number availabe in the micro registers to decimal digits
and stores the decimal digits in an array */
void Hex2Decimal(unsigned long num)
{
unsigned char value[10];
unsigned char i = 0;

while(num > 0)
{
value = num % 10;
num /= 10;
i = i + 1;
}
}
 

Status
Not open for further replies.

Similar threads

Cookies are required to use this site. You must accept them to continue using the site. Learn more…