hex_to_bin(9)

πŸ“¦ version 7.3.1, in nixpkgs unstable

πŸ’… 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 if ch <= '9'
  • ('0' - 1 - ch) is negative if ch >= '0'
  • we "and" these two values, so the result is negative if ch is 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 have 0xffffff if ch is in the range '0' ... '9', 0 otherwise
  • we "and" this value with (ch - '0' + 1) β€” we have a value 1 ... 10 if ch is in the range '0' ... '9', 0 otherwise
  • we add this value to -1 β€” we have a value 0 ... 9 if ch is in the range '0' ... '9', -1 otherwise
  • 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