hex_to_bin(9)
π hex_to_bin β straight outta the Kernel API Manual, bestie β¨
okay so picture this: you're deep in the kernel, you've got a single lonely hex digit, and you need to know what it actually means. That's this function. Welcome to the group chat π«Ά
β¨ NAME β¨
hex_to_bin β converts a hex digit to its real value, no cap π
πΈ SYNOPSIS πΈ
int hex_to_bin (unsigned char ch );
π ARGUMENTS π
chβ the ascii character that represents a hex digit π¦
π DESCRIPTION π
hex_to_bin takes one hex digit and turns it into its actual value. And if the input is bad? You get -1. That's it. That's the vibe check π
So here's the thing that makes this icon special: this function is used to load cryptographic keys, which means it's coded in such a way that there are no conditions or memory accesses that depend on data. None. Zero. Constant-time queen behavior, periodt πβ¨
π§ the logic, explained (yes, all of it)
Okay so the explanation of the logic, step by step, because this is genuinely iconic:
(ch - '9' - 1)is negative ifch <= '9'('0' - 1 - ch)is negative ifch >= '0'- we "and" these two values, so the result is negative if
chis in the range we are only interested in - we only care about the sign, so we do a shift
>> 8 - note that right shift of a negative value is implementation-defined, so we cast the value to
(unsigned)before the shift β we have0xffffffifchis in the range'0'...'9',0otherwise - we "and" this value with
(ch - '0' + 1)β we have a value1...10ifchis in the range'0'...'9',0otherwise - we add this value to
-1β we have a value0...9ifchis in the range'0'...'9',-1otherwise - the next line is similar to the previous one, but we need to decode both uppercase and lowercase letters, so we use
(ch & 0xdf), which converts lowercase to uppercase π
no branches, no data-dependent memory lookups β the whole point is that nothing about the timing leaks your key π
π¦ SEE ALSO π¦
Kernel file ./lib/hexdump.c, plus these besties: hex2bin(9), bin2hex(9), hex_dump_to_buffer(9), print_hex_dump(9) π
and that's the whole page, bestie π this one dropped from ./lib in October 2026, and it lives at hex_to_bin(9) β go forth and decode your digits, iykyk β¨ππ«Ά
π¦ where this page comes from
- nixpkgs unstable: linux-manual 7.3.1
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms