如何在没有 0x 的情况下将整数转换为十六进制字符串 (Julia 1.0)

How to convert integers to a hex string without the 0x (Julia 1.0)

我有一个问题,我想解码 pcap 记录的 MAC 地址并将其表示为 UInt8 数组中的 4c:76:25:e9:78:42。

数组看起来像这样,它是 pcap 记录的一部分。

UInt8[0x4c, 0x76, 0x25, 0xe9, 0x78, 0x42, 0xe0, 0x0e, 0xda, 0x58  …  0x3c, 0xb6, 0x47, 0x00, 0x00, 0x00, 0xe6, 0x5a, 0xa0, 0x29]

其他人创建的用于 Julia 0.6.4 的逻辑不再适用于 Julia 1.0

这是项目中的一些代码。

数据

julia> cap = PcapOffline("C:/users/XXX/desktop/31072018_1800_2000_IMSI_XXXXXXXXXXXXXXX.pcap")
PcapOffline("C:/users/XXX/desktop/31072018_1800_2000_IMSI_XXXXXXXXXXXXXXX.pcap", IOStream(<file C:/users/rsteel7/desktop/31072018_1800_2000_IMSI_XXXXXXXXXXXXXXX.pcap>), PcapFileHeader(0xa1b23c4d, 0x0002, 0x0004, 0, 0x00000000, 0x00000800, 0x00000001), PcapRec(0x00000000, 0x00000000, 0x00000000, 0x00000000, UInt8[]), true)

julia> rec = pcap_get_record(cap)
PcapRec(0x5b60a3a1, 0x1acb91ba, 0x00000082, 0x00000082, UInt8[0x4c, 0x76, 0x25, 0xe9, 0x78, 0x42, 0xe0, 0x0e, 0xda, 0x58  …  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xa5, 0x54, 0x83])

julia> layers = decode_pkt(rec.payload)
DecPkt(EthHdr("76:118:37:233:120:66", "224:14:218:88:219:223", 0x0800), IpHdr(0x04, 0x14, 0xba, 0x0070, 0x0000, IpFlags(false, true, false), 0x0000, 0xf8, 0x84, true, "0.0.0.0", "0.0.0.0"), nothing)

这是执行 decode_pkt

的旧代码
function decode_eth_hdr(d::Array{UInt8})
    eh = EthHdr()
    eh.dest_mac = string(hex(d[1], 2), ":", hex(d[2], 2), ":", hex(d[3], 2), 
                    ":", hex(d[4], 2), ":", hex(d[5], 2), ":", hex(d[6], 2))
    eh.src_mac  = string(hex(d[7], 2), ":", hex(d[8], 2), ":", hex(d[9], 2), 
                    ":", hex(d[10], 2), ":", hex(d[11], 2), ":", hex(d[12], 2))
    eh.ptype    = getindex_be(UInt16, d, 13)
    eh
end

谢谢

据我了解,hex 在 Julia v0.7.0 中被弃用,然后在 Julia v1.0.0 中被淘汰。

你可以借用Julia v0.7.0 deprecation message自己定义...

hex(n, pad) = string(n, base = 16, pad = pad)

如果你想成为 "complete",也添加非填充版本...

hex(n) = string(n, base = 16)

稍微修改一下@rickhg12hs 的函数,您就可以编写(恕我直言)看起来更像 julian 的代码:

hex(n) = string(n, base=16, pad=2)

function decode_eth_hdr(d::Array{UInt8})
    # ...
    eh.dest_mac = join(hex.(d[1:6]), ":")  # apply hex to first 6 elements and join result with ":"
    eh.src_mac  = join(hex.(d[7:12]), ":")  # do it for next 6 elements
    # ...

你也可以这样写:

eh.src_mac = d[7:12] .|> hex |> x->join(x, ":")