2

I have a tcl string set in a variable. I want to treat it as a hex to convert into binary of it. Can anybody help me to achieve this.

Here is what i am doing :

$ /usr/bin/tclsh8.5
% set a a1a2a3a4a5a6
a1a2a3a4a5a6
% set b [ string range $a 0 3 ]
a1a2

Now i want that a1a2 value of variable "b" should be treated as 0xa1a2, so that i can convert it into binary. Please help me to solve this.

Dexygen
  • 12,287
  • 13
  • 80
  • 147
user1497818
  • 375
  • 1
  • 7
  • 16
  • 1
    What do you want out of this? Numbers? A string of bytes? These are different (and Johannes gives the perfect answer for “string of bytes”). – Donal Fellows Feb 01 '13 at 01:34

1 Answers1

5

If you are using Tcl 8.6, then binary decode hex is the best choice:

binary decode hex $b

If you are using an older version of Tcl, then you have to use the binary format with the H format specifier:

binary format H* $b

You can write the resulting byte array to a file or send it through a socket etc, but if you want to display it as text, I suggest converting it to a string first:

encoding convertfrom utf-8 [binary format H* $b]
Johannes Kuhn
  • 14,778
  • 4
  • 49
  • 73