Re:Converting binary floating-point numbers to integers
by CyberRabbi on Saturday October 23, 2021 @02:46AM
(#28966291)
Accessing the value stored in "value" through the "fields" member is undefined behavior. I'm legitimately surprised that lemire published this code. The correct and well-defined way to do this is to memcpy() the double value to a char array and access the relevant bits that way.
[ Parent
| on HN ]
Re:Converting binary floating-point numbers to integers
by Cloudef on Saturday October 23, 2021 @02:50AM
(#28966306)
Its not, union is valid in C(note, not c++) for this.
Re:Converting binary floating-point numbers to integers
by nly on Saturday October 23, 2021 @05:43AM
(#28967012)
It is probably still unwise in C as well in this case because the layout of bits in a bitfield is still implementation defined, and varied based on endianness of the uint64 for example
Re:Converting binary floating-point numbers to integers
by occamrazor on Saturday October 23, 2021 @06:29AM
(#28967157)
What is the alternative? Are there functions in the C standard to get mantissa and exponent?
Re:Converting binary floating-point numbers to integers
by gpderetta on Saturday October 23, 2021 @09:03AM
(#28967992)
Frexp modf. Last time I checked code generation wasn't particularly good.
Re:Converting binary floating-point numbers to integers
by CyberRabbi on Saturday October 23, 2021 @03:37PM
(#28971541)
I already mentioned the alternative. memcpy() into a char array.
Re:Converting binary floating-point numbers to integers
by Cloudef on Sunday October 24, 2021 @06:05AM
(#28976433)
Memcpy doesnt fix endianess
Re:Converting binary floating-point numbers to integers
by CyberRabbi on Saturday November 06, 2021 @08:25PM
(#29135207)
It was never claimed to deal with endianness and while we're on the subject of binary-layout, union-based binary manipulation is even worse on that front as no specific binary layout is mandated for structures or floating points.
Re:Converting binary floating-point numbers to integers
by CyberRabbi on Saturday October 23, 2021 @03:38PM
(#28971545)
lemire's code is C++
Re:Converting binary floating-point numbers to integers
by chrisseaton on Saturday October 23, 2021 @10:35AM
(#28968915)
> Accessing the value stored in "value" through the "fields" member is undefined behavior.
Iām surprised at that. Can you quote the relevant part of the spec that you think makes this undefined behaviour?
Re:Converting binary floating-point numbers to integers
by CyberRabbi on Saturday October 23, 2021 @03:37PM
(#28971532)
It's undefined behavior in C++. In C it is not certain if it is undefined or unspecified behavior.
https://stackoverflow.com/questions/11373203/accessing-inact...
Re:Converting binary floating-point numbers to integers
by chrisseaton on Saturday October 23, 2021 @04:21PM
(#28971873)
I think the standard and the link you've giving makes it pretty explicit that it's unspecified. I don't really see where you can get undefined from?