1

How can I convert a positive float (ieee 754, single precision 32 bit) to BCD in C#?

UPDATE

If I'm not wrong, what I need is called packed BCD. I'm already doing int to BCD conversions. In the way I'm doing, the number 1234 would result in the following byte array:

{0x00, 0x00, 0x12, 0x34}

The method I use (which probably isn't the best way of doing it) is:

public byte[] ToBCD(long num) {
    long bcd = 0;
    int i = 0;
    while (num > 9) {
        bcd |= ((num % 10) << i);
        num /= 10;
        i += 4;
    }
    byte[] bytes = BitConverter.GetBytes(bcd | (num << i));
    Array.Reverse(bytes);
    return bytes;
}
Fernando
  • 4,029
  • 1
  • 26
  • 35
  • BCD = [Binary-coded decimal](http://en.wikipedia.org/wiki/Binary-coded_decimal)? – dtb May 23 '12 at 18:02
  • There seem to be ways to encode a value. Which one do you want? – dtb May 23 '12 at 18:14
  • 1
    So how should, for example, `float num = 1f / 3f;` be encoded? – dtb May 23 '12 at 18:32
  • If I'm not wrong, it would be 0x33, 0x33, 0x33, 0xC1. I'm saying that based on http://www.fsinc.com/reference/html/com9anm.htm, since my docs aren't clear. It only states that the value should be a "ieee - 754 single precision floating point in 32 bits" and should fit into a byte array with size of 4. – Fernando May 23 '12 at 20:15
  • Do you need a "IEEE-754 Single Precision Float (32-bits)" or a "BCD Float (32-bit)"? Both fit in a byte array with size of 4. – dtb May 23 '12 at 20:35
  • This one is a part of a larger byte array. All the others bytes are integers converted to BCD. Since the documentation doesn't say anything about changing it, I assume is BCD Float. – Fernando May 23 '12 at 20:40

2 Answers2

3

BCD was not designed to store floating point numbers. However, what you can do is encode it and decode it using your own custom BCD-like schema. For example, I would take your number and remove the decimal point. Then I would encode each digit as BCD, like normal. Then add an extra 4 bits to determine where the decimal point should go. For example, to encode the number 15.101:

15.101 -> 15101 -- Remove the decimal point

15101 -> 0001 0101 0001 0000 0001 -- Converted to BCD

Now we just add an extra 4 bits at the end to determine decimal place:

0001 0101 0001 0000 0001 -> 0001 0101 0001 0000 0001 0011

0011 is 3. That's because the decimal point goes 3 places to the left.

As far as your function goes, just pick off the far right 4 bits and save them for later. Then run your function as normal. Then convert the right 4 bits you saved into a decimal number. Then divide by (10*number)..thats it

Icemanind
  • 47,519
  • 50
  • 171
  • 296
0

Not sure how to handle this question, but here's what I've found:

since the protocol documentation sucks, I've searched some old code and found evidences that even the other data being encoded as BCD, the float numbers aren't. So, BitConverter.GetBytes will do what I need.

Fernando
  • 4,029
  • 1
  • 26
  • 35