Reputation: 375
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.
Upvotes: 2
Views: 13300
Reputation: 15163
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]
Upvotes: 5