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

2

I have an issue where I want to decode the MAC address of a pcap record and represent it as 4c:76:25:e9:78:42 from a UInt8 array.

The array looks like this which is a part of the pcap record.

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

The logic that someone else created to work on Julia 0.6.4 no longer works for Julia 1.0

Here is some code from the project.

the data

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)

This is the old code that performs the 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

Thanks

string
hex
julia
pcap
asked on Stack Overflow Sep 12, 2018 by Zak21 • edited Sep 12, 2018 by rickhg12hs

2 Answers

5

With a little modified @rickhg12hs 's function you could write code which (IMHO) looks more 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
    # ...

You could also write something like this:

eh.src_mac = d[7:12] .|> hex |> x->join(x, ":")
answered on Stack Overflow Sep 13, 2018 by Liso
2

As I understand it, hex was deprecated in Julia v0.7.0 and then eliminated in Julia v1.0.0.

You can define it yourself by borrowing the Julia v0.7.0 deprecation message...

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

and if you want to be "complete", add the non-padding version too...

hex(n) = string(n, base = 16)
answered on Stack Overflow Sep 12, 2018 by rickhg12hs

User contributions licensed under CC BY-SA 3.0