阅读
要获取数据,您可以使用以下内容:
set f [open theFile.txt]
set data [gets $f]
close $f
请注意,对于此类工作,我会考虑将文件作为二进制数据处理:
set f [open theFile.bin "rb"]
set data [read $f 12]
close $f
解析/转换
不过,将数据解释为十六进制序列(小写)很容易:
binary scan $data H8H8H8 word(1) word(2) word(3)
将值存储到一个名为word 的关联 数组中(索引为1、2 和3)。如果你想要类似你在其他语言中习惯的东西,那么你可以转换成这样的 Tcl 列表:
set wordList [list $word(1) $word(2) $word(3)]
Tcl 的列表值是真正的一流值。关联数组不是,而是命名实体,因此我们可以在 binary scan 中使用它们。
使用
在上述之后,您可以在列表中查找:
# *Zero*-based indexing is the rule in Tcl
lindex $wordList 0
并使用以下方法迭代它们:
foreach item $wordList { puts $item }
大小写转换
如果你真的需要大写十六进制,请像这样申请string toupper:
# Nasty type-shimmering trick!
set wordList [string toupper $wordList]
或者在 Tcl 8.6 中,你可以做这个更好的版本:
set wordList [lmap item $wordList {string toupper $item}]
但我实际上只是string toupper,因为我在正常情况下使用了该值。
puts "[lindex $wordList 0] -> [string toupper [lindex $wordList 0]]"