【问题标题】:Reading file dataword by dataword in Tcl在 Tcl 中逐个数据字读取文件数据字
【发布时间】:2014-03-25 16:18:18
【问题描述】:

我想在 Tcl 中读取一个包含 ASCII 字符的文件(用于我们的目的的常规文本文件),并将其以十六进制形式逐字存储在一个数组中(即逐个数据字,每个数据字 32 位)。

一个例子是一个包含以下内容的文本文件:

ÿÿÿÿûûûûÿÿÿÿ    

(在 ASCII 字符中,ÿ = FF,û = FB)

我想把它解析成一个数组,结果

[["FFFFFFFF"], ["FBFBFBFB"], ["FFFFFFFF"]]

我如何实现这一目标?我似乎找不到合适的功能。

【问题讨论】:

    标签: tcl


    【解决方案1】:

    阅读

    要获取数据,您可以使用以下内容:

    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关联 数组中(索引为123)。如果你想要类似你在其他语言中习惯的东西,那么你可以转换成这样的 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]]"
    

    【讨论】:

      【解决方案2】:

      您可以使用scanformat,如下所示:

      set asc "ÿÿÿÿûûûûÿÿÿÿ"
      set result ""
      set bytearray [list]
      set count 0
      
      foreach l [split $asc ""] {
          append result [format %x [scan $l %c]] ;# %c for reading character as unicode
                                                  # %x for converting into hex
          incr count
          if {$count == 4} {
              set count 0
              lappend bytearray [string toupper $result]
              set result ""
          }
      }
      
      puts $bytearray
      # => FFFFFFFF FBFBFBFB FFFFFFFF
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-11-03
        • 2022-01-25
        • 2021-09-07
        • 1970-01-01
        • 2014-06-12
        • 1970-01-01
        • 2023-03-20
        相关资源
        最近更新 更多