Malu05
Malu05

Reputation: 119

Converting character to hex via Tcl

I am trying to convert some characters into hex using tcl.

And i would usually do something like this: [binary format a* 'o'] that return 111, which is the int representation of 'o' that can then be converted.

However the way that i retrive the character, [value string_split] returns "o" instead of 'o' cuasing the the function to throw an error, esentially like doing: [binary format a* "o"] which returns "ERROR: Nothing is named "o""

So, what is the difference between "o" and 'o' in a tcl context and how can i get my [binary format a* [value string_split]] call to return 111 like [binary format a* 'o'] would do.

It should be noted that i am using TheFoundry's Nuke to do this and I don't know exactly what version of TCL they are using, but it is a rather old one.

Upvotes: 0

Views: 920

Answers (2)

tzot
tzot

Reputation: 95941

For the general case of a string, including a string of length 1, since Tcl 8.6 one can also do:

binary encode hex $input_string
binary decode hex $hex_string

This assumes that $input_string is already “binary”, so for text it would be wise to first:

set input_string [encoding convertto utf-8 $input_string]

Upvotes: 0

Shawn
Shawn

Reputation: 52409

You can use scan with a format of %c to get the Unicode codepoint value of a character, and then format to print it as hex:

#!/usr/bin/env tclsh

set o_str o
scan $o_str %c o_value
puts $o_value ;# 111
puts [format 0x%x $o_value] ;# 0x6f

Upvotes: 3

Related Questions