mysql: decimal转换为二进制

转自mysql代码注释:decimal.c

------------------------------------------------------------------------------------------------------------

*
Convert decimal to its binary fixed-length representation
two representations of the same length can be compared with memcmp
with the correct -1/0/+1 result


SYNOPSIS
decimal2bin()
from - value to convert
to - points to buffer where string representation should be stored
precision/scale - see decimal_bin_size() below


NOTE
the buffer is assumed to be of the size decimal_bin_size(precision, scale)


RETURN VALUE
E_DEC_OK/E_DEC_TRUNCATED/E_DEC_OVERFLOW


DESCRIPTION
for storage decimal numbers are converted to the "binary" format.


This format has the following properties:
1. length of the binary representation depends on the {precision, scale}
as provided by the caller and NOT on the intg/frac of the decimal to
convert.
2. binary representations of the same {precision, scale} can be compared
with memcmp - with the same result as decimal_cmp() of the original
decimals (not taking into account possible precision loss during
conversion).


This binary format is as follows:
1. First the number is converted to have a requested precision and scale.
2. Every full DIG_PER_DEC1 digits of intg part are stored in 4 bytes
as is
3. The first intg % DIG_PER_DEC1 digits are stored in the reduced
number of bytes (enough bytes to store this number of digits -
see dig2bytes)
4. same for frac - full decimal_digit_t's are stored as is,
the last frac % DIG_PER_DEC1 digits - in the reduced number of bytes.
5. If the number is negative - every byte is inversed.
5. The very first bit of the resulting byte array is inverted (because
memcmp compares unsigned bytes, see property 2 above)


Example:


1234567890.1234


internally is represented as 3 decimal_digit_t's


1 234567890 123400000


(assuming we want a binary representation with precision=14, scale=4)
in hex it's


00-00-00-01 0D-FB-38-D2 07-5A-EF-40


now, middle decimal_digit_t is full - it stores 9 decimal digits. It goes
into binary representation as is:




........... 0D-FB-38-D2 ............


First decimal_digit_t has only one decimal digit. We can store one digit in
one byte, no need to waste four:


01 0D-FB-38-D2 ............


now, last digit. It's 123400000. We can store 1234 in two bytes:


01 0D-FB-38-D2 04-D2


So, we've packed 12 bytes number in 7 bytes.
And now we invert the highest bit to get the final result:


81 0D FB 38 D2 04 D2


And for -1234567890.1234 it would be


7E F2 04 37 2D FB 2D

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值