logoalt Hacker News

adrian_b • today at 3:20 PM • 3 replies • view on HN

Bool is 1-bit, but that bit can be defined as signed or as unsigned.

If bool is defined as unsigned, casting it to any size of integers will give 0 for false and 1 for true (using the standard zero-extension operation that converts smaller unsigned integers to bigger unsigned integers).

If bool is defined as signed, casting it to any size of integers will give 0 for false and -1 for true (i.e. an all-1 bit pattern) (using the standard sign-extension operation that converts smaller signed integers to bigger signed integers).

Defining bool to ignore the other bits except the LSB leads to a lower performance on most processors, because in almost all instruction sets it is more efficient to test whether an integer is null or non-null, than to test the value of a bit.

The only efficient way to use a single bit and to ignore the others would be to store the boolean in the most-significant bit, i.e. in the sign bit of a signed integer, because testing the sign is normally as simple as testing whether a value is null. If this convention were used, a boolean result could be 0 for false and -1 for true, but in input arguments negative would be true and non-negative would be false.


Replies

Lumich • today at 5:56 PM

« to test whether an integer is null or non-null »

Shouldn't this more correctly read zero or non-zero ?

➕ show 1 reply
thechao • today at 6:36 PM

This reminds me of my favorite arcane C test: what value is TRUE and FALSE on X bullshit tool chain. My a favorite was 0=TRUE, 2=FALSE. I'd like to shake the hand of the joker who came up with that.

wat10000 • today at 3:26 PM

x86-64 and ARM64, at least, let you test an arbitrary bit in a register with one instruction.

➕ show 2 replies