2

Casting between uints and bytes16 yields different results as that of manipulating the bits directly.

Why? I thought that with casting we were just changing the representation from bits to bytes, and vice versa, but the core numbers stayed the same.

uint b = 54802476401439357 * 1e18;
uint base = 1108895170451311786;
uint b_prime = uint(uint128(bytes16(uint128(base)).ln()));
uint b_prime2 = base.fromUInt().ln().toUInt();

console.log('prime: ', b_prime); //----> 255276110499392941787653382584691046923
console.log('prime2: ', b_prime2);// ---> 42

The fromUInt(), toUInt(), and ln() functions can be found on ABDKMathQuad's library.

Thanks!

1 Answer 1

3

The difference is that the library assumes that bytes16 is IEEE 754 quadruple-precision binary floating-point numbers.

If you look at the conversion functions fromUint, toUint, etc. they are quite complex because they have to pack or unpack the IEEE floating point format.

On the other hand the solidity casting bytes16(uint128(base)) doesn't known anything about floating point numbers. In this case itt doesn't do anything at the EVM level, because the types are of the same length. It is a semantic conversion to prevent type conversion of bugs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.