Hi,

tcl 8.6 has binary encode/decode functions [1], so I'm trying to convert a hex 
string representation of an IPv4 or IPv6 address into binary and back to the 
hex representation.

I'd have expected that this decode hex to binary and back should always be 
reversible, but
doesn't seem to be the case:

# tclsh8.6 test3.tcl                                                   
4 10.22.66.138
a16428a
�d(
a16428
NAY
6 2001:350:43a6::b7
2001035043a6000000000000000000b7
 PC��
2001035043a6000000000000000000b7
YAY

Is it just me understanding/doing something wrong here?
This is on a not too old:
OpenBSD 6.5-current (GENERIC.MP) #36: Mon May 20 16:36:12 MDT 2019
    dera...@amd64.openbsd.org:/usr/src/sys/arch/amd64/compile/GENERIC.MP

with tcl-8.6.8p2

[1] https://www.tcl.tk/man/tcl8.6/TclCmd/binary.htm#M5

package require ip
set l [list 10.22.66.138 2001:350:43a6::b7 ]
foreach i $l {
    set ipv [ip::version $i]
    puts "$ipv $i"
    if { $ipv == 4 } {
      set normalized [format %x [ip::toInteger $i]]
    } else {
      set normalized [string map {: ""} [ip::normalize $i]]
    }
    puts $normalized
    set bin [binary decode hex $normalized]
    puts $bin
    set unbin [binary encode hex $bin]
    puts $unbin
    if { $normalized == [binary encode hex [binary decode hex $normalized]] } {
      puts "YAY"
    }  else {
      puts "NAY"
    }
}

cheers,
Sebastian
package require ip
set l [list 10.22.66.138 2001:350:43a6::b7 ]

foreach i $l {
    set ipv [ip::version $i]
    puts "$ipv $i"

    if { $ipv == 4 } {
      set normalized [format %x [ip::toInteger $i]]
    } else {
      set normalized [string map {: ""} [ip::normalize $i]]
    }

    puts $normalized

    set bin [binary decode hex $normalized]

    puts $bin

    set unbin [binary encode hex $bin]

    puts $unbin

    if { $normalized == [binary encode hex [binary decode hex $normalized]] } {
      puts "YAY"
    }  else {
      puts "NAY"
    }



}

Reply via email to