Do we have built-in hexadecimal to binary conversion in tcl?

tcl

Solution

I'm not quite sure what you mean by binary; do you mean a sequences of bytes or a sequence of `0` and `1` characters?

Converting from hexadecimal to a byte sequence (which is a string that happens to only have characters in the range `\u0000` to `\u00ff`) is done with the `binary format` command:

set hex "61626364"
set bytes [binary format H* $hex]
puts $bytes
# Prints 'abcd'

To convert to a sequence of digits that represent bits, you convert to a binary string as above and then use `binary scan` to convert back:

set hex "61626364"
# No option to get the value without writing it to a variable
binary scan [binary format H* $hex] B* bits
puts $bits
# Prints '01100001011000100110001101100100'

All the above work on Tcl 8.5. Note that you need to use upper case `H*` and `B*` or the code will try to do something which it claims is “little endian” (and might actually be so) and which confuses me a lot.

Problem

I need help to figure out a built-in hexadecimal to binary conversion in Tcl; I am currently using TCL 8.5. Similar to hex to dec conversion, do we have for hex to bin or any one liner syntax for doing the conversion?

Original source