BCD-Decimal

  • Thread starter Thread starter Stephen
  • Start date Start date
Stephen said:
I am trying to figure out how to convert a BCD number to its decimal
equivilant.

One way (not necesarily optimal) is this:

using System;

class Test
{
public static void Main()
{
byte[] bcdNumber = { 0x12, 0x34, 0x56, 0x78 };

long result=0;
foreach (byte b in bcdNumber)
{
int digit1 = b >> 4;
int digit2 = b & 0x0f;
result = (result * 100) + digit1 * 10 + digit2;
}
Console.WriteLine("{0}", result); //12345678
}
}
 
What I was really looking for was a solution that would allow for a binary
number encoded in BCD to be converted to decimal. Eg

10000 11001 = 1 3

Could do a switch statement but thought there might be a better solution.

Alberto Poblacion said:
Stephen said:
I am trying to figure out how to convert a BCD number to its decimal
equivilant.

One way (not necesarily optimal) is this:

using System;

class Test
{
public static void Main()
{
byte[] bcdNumber = { 0x12, 0x34, 0x56, 0x78 };

long result=0;
foreach (byte b in bcdNumber)
{
int digit1 = b >> 4;
int digit2 = b & 0x0f;
result = (result * 100) + digit1 * 10 + digit2;
}
Console.WriteLine("{0}", result); //12345678
}
}
 
Stephen said:
What I was really looking for was a solution that would allow for a binary
number encoded in BCD to be converted to decimal. Eg

10000 11001 = 1 3

How does 10000 represent 1 and 11001 represent 3 in this case? Did you
deliberately put each of the digits in 5 bits rather than 4?
Could do a switch statement but thought there might be a better
solution.

If we understood the BCD variant you're using better, I'm sure we could
come up with something.
 
What I was really looking for was a solution that would allow for a binary
number encoded in BCD to be converted to decimal. Eg

10000 11001 = 1 3
Do you mean 0001 0011 -> 1 3?

How is your BCD number held, as a byte array or what?

How do you want the decimal equivalent, as a string, int, long, double
or what?

Here is some example code to convert BCD held in a big-endian byte
array to a long:

long BCD2Long(byte source) {
long result = 0;
foreach (byte b in source) {
int hi = b >> 4;
int lo = b & 0x0F;
result *= 10;
result += hi;
result *= 10;
result += lo;
}
return result;
}

Warning, neither tested nor compiled. Caveat emptor.

rossum
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top