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.

BCD to decimal convertion and vice versa

  • Author alexxx
  • Create date
  • Updated
  • Blog entry read time 1 min read
Some compilers may have built in functions for these convertions, but others don't. Below are two functions for converting a BCD number to decimal and vice versa:


Code C - [expand]
1
2
3
4
5
6
7
8
9
10
11
#define uint8 unsigned char
 
uint8 BCDToDecimal (uint8 bcdByte)
{
  return (((bcdByte & 0xF0) >> 4) * 10) + (bcdByte & 0x0F);
}
 
uint8 DecimalToBCD (uint8 decimalByte)
{
  return (((decimalByte / 10) << 4) | (decimalByte % 10));
}



And a brief calling example:


Code C - [expand]
1
2
3
4
5
uint8 decNum = 52;
uint8 bcdNum = 0x39;    
 
uint8 convertedToBCD = DecimalToBCD(decNum);  //convertedToBCD = 0x52
uint8 convertedToDec = BCDToDecimal(bcdNum);  //convertedToDec = 39



I am waiting feedback for better or more effective converting ways.

Cheers!

Comments

thannara123 said:
how can i get the ASCII value ?
convertedToDec + 0x30h;
Hi thannara123.

Sorry for the late reply. Although I am subscribed to this blog entry, I didn't get any notification. :sad:

Anyway, you are right if we are talking about one digit only (even though I prefer OR compared to addition). For more digits, you must split the number to its digits and then convert them in separate.
For example if you have decimal number 38, then you will split it to 3 and 8 and then OR those values with 0x30. The final result will be 0x33 and 0x38 ('3' and '8').


Alexandros
 

Part and Inventory Search

Blog entry information

Author
alexxx
Read time
1 min read
Views
1,272
Comments
3
Last update

More entries in Uncategorized

More entries from alexxx

Share this entry

Back
Top