ext-decimal icon indicating copy to clipboard operation
ext-decimal copied to clipboard

Consider adding support for packed BCD

Open rybakit opened this issue 6 years ago • 2 comments

Hi! I work on a msgpack extension that can pack/unpack fixed-point decimals that are stored in the following format:

+-------+--------------------------------+
| scale | packed BCD (2 digits per byte) |
+-------+--------------------------------+

I implemented packing/unpacking logic in pure PHP, but wonder if it would make sense to add support of packed decimals to this extension. Wdyt?

For example, here is how I pack them now:

$data = $value->toFixed(self::PRECISION);

if ('-' === $data[0]) {
    $nibble = 'd';
    $data = \substr($data, 1);
} else {
    $nibble = 'c';
}

$pieces = \explode('.', $data, 2);
$pieces[1] = \rtrim($pieces[1], '0');

$data = "{$pieces[0]}{$pieces[1]}{$nibble}";
if (0 !== \strlen($data) % 2) {
    $data = '0'.$data;
}

$scale = empty($pieces[1]) ? 0 : \strlen($pieces[1]);

return [$scale, \hex2bin($data)];

rybakit avatar Sep 30 '19 08:09 rybakit

How does this compare or relate to how mpdecimal stores decimal values?

rtheunissen avatar Oct 14 '20 14:10 rtheunissen

I'm not familiar with mpdecimal and don't know how it stores decimals, but if I'm not mistaken, this is implemented in the decNumber library. Maybe this link will explain better what I need:

  • https://github.com/tarantool/doc/issues/992#issuecomment-554912061

And some more links to the implementation:

  • https://github.com/tarantool/tarantool/blob/8317189a9b1f8351dabaecc8216a1c65b175d227/src/lib/core/decimal.c#L401
  • https://github.com/tarantool/decNumber

rybakit avatar Dec 02 '20 00:12 rybakit