用二进制表示十进制数

Representing decimal numbers in binary

如何用两个字节表示整数,例如 23647,其中一个字节包含最后两位数字 (47),另一个字节包含其余数字 (236)?

There are several ways do to this.

One way is to try to use Binary Coded Decimal (BCD). This codes decimal digits, rather than the number as a whole into binary. The packed form puts two decimal digits into a byte. However, your example value 23647 has five decimal digits and will not fit into two bytes in BCD. This method will fit values up to 9999.

Another way is to put each of your two parts in binary and place each part into a byte. You can do integer division by 100 to get the upper part, so in Python you could use

upperbyte = 23647 // 100

Then the lower part can be gotten by the modulus operation:

lowerbyte = 23647 % 100

Python will directly convert the results into binary and store them that way. You can do all this in one step in Python and many other languages:

upperbyte, lowerbyte = divmod(23647, 100)

You are guaranteed that the lowerbyte value fits, but if the given value is too large the upperbyte value many not actually fit into a byte. All this assumes that the value is positive, since negative values would complicate things.


(This following answer was for a previous version of the question, which was to fit a floating-point number like 36.47 into two bytes, one byte for the integer part and another byte for the fractional part.)

One way to do that is to "shift" the number so you consider those two bytes to be a single integer.

Take your value (36.47), multiply it by 256 (the number of values that fit into one byte), round it to the nearest integer, convert that to binary. The bottom 8 bits of that value are the "decimal numbers" and the next 8 bits are the "integer value." If there are any other bits still remaining, your number was too large and there is an overflow condition.

This assumes you want to handle only non-negative values. Handling negatives complicates things somewhat. The final result is only an approximation to your starting value, but that is the best you can do.

Doing those calculations on 36.47 gives the binary integer

10010001111000

So the "decimal byte" is 01111000 and the "integer byte" is 100100 or 00100100 when filled out to 8 bits. This represents the float number 36.46875 exactly and your desired value 36.47 approximately.