Frage

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;
}
War es hilfreich?

Lösung 2

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.

Andere Tipps

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

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top