| Author |
Message |
erodeboy
Joined: 15 Nov 2005 Posts: 86 Helped: 1 Location: India
|
12 Mar 2006 3:27 hex to bcd |
|
|
|
|
| how to convert a hex value to bcd using keil c
|
|
| Back to top |
|
 |
SphinX
Joined: 25 Jan 2002 Posts: 1069 Helped: 28 Location: EGYPT
|
12 Mar 2006 7:52 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
|
|
| Back to top |
|
 |
silvio
Joined: 31 Dec 2001 Posts: 801 Helped: 90
|
12 Mar 2006 7:57 hex to bcd conversion c code |
|
|
|
|
| Quote: |
From fmayr(at)electronic.tu-graz.ac.at Thu Feb 6 10:24:30 1997
Date: Wed, 05 Feb 1997 15:36:00 +0100
From: Friedrich Mayr <fmayr(at)electronic.tu-graz.ac.at>
To: 8051code(at)keil.com
Subject: Fast LONG to BCD conversion
This function was written within the Keil C51 environment
by Dr. Roehrer (Inst. f. Elektronik, TU-Graz) and me
to be called from a C - Program as: "void bin2bcd(void)"
The following global variable (must be located in the
internal RAM of the processor, "data" or "idata" ) is
used both to pass the argument (a "long" value) to the
function, as well as to receive the result (6 digits):
union
{
unsigned char buf[6];
long in;
} idata U_b;
The purpose of the code is to convert a signed long value
to BCD - code with leading sign if needed. Values exceeding
the range of 6(-:5) Digits should all be displayed by '-'.
The usage of memory was critical because no external RAM is
present in the system, so only the Accu, B, R1, R2, R3, R4
are used aside of the digit- (and argument-) buffer "U_b".
The trick applied in the function is to use a
"small" (nibble by nibble) division and the extensive
use of the '51 - opcodes XCHD and SWAP.
This results in very fast execution.
The function can easily be modified for example
to time-calculations or extended to the full "long"
range .
|
http://www.boerde.de/~matthias/m8051/bin2bcd.zip
|
|
| Back to top |
|
 |
Google AdSense

|
12 Mar 2006 7:57 Ads |
|
|
|
|
|
|
| Back to top |
|
 |
tohbas
Joined: 31 Mar 2005 Posts: 26 Helped: 1 Location: Thailand
|
13 Mar 2006 3:10 hex to bcd in c |
|
|
|
|
float a;
unsigned char b;
b = 0xff;
a = b;
|
|
| Back to top |
|
 |