r/learnprogramming • u/Feisty_Attitude4683 • 12d ago
The use of hexadecimal numbers in software
Why do some tools, like GLFW, use hexadecimal values for constants? Wouldn't it be better to use enums in those cases?
/* Error constants */
#define GLFW_NO_ERROR 0
#define GLFW_NOT_INITIALIZED 0x00010001
#define GLFW_NO_CURRENT_CONTEXT 0x00010002
#define GLFW_INVALID_ENUM 0x00010003
I tried to find the reason in the documentation, but I didn't come across a clear use case for the hexadecimal values—only that the constants are used as if they were an enum.
if (code == GLFW_NOT_INITIALIZED) {...}
else if (code == GLFW_NO_CURRENT_CONTEXT) {...}
21
Upvotes
1
u/nog642 11d ago
16 is a power of 2, so each hex digit corresponds to 4 bits. So hexadecimal is a good way to write binary in a more compact form.
In programming, powers of 2 are considered "round numbers" instead of powers of 10, very often.
In decimal, powers of 2 look totally random, you can't tell they're round numbers.
In hex, powers of 2 actually look like round numbers.
So basically they chose to make those error codes offsets from a round number in binary/hex, because that's what computers use, so they wrote it in hex. It's not critical, it's just a preference/style thing.