Reputation: 1505
I'm trying to convert a 64 bit binary string value () in to an integer but I'm apparently hitting the tcl limit and getting:
integer value too large to represent
Binary String:
000000000000101000000000000010100000000000000100
The proc I'm using to convert from binary to integer is:
proc binary2decimal {bin} {
binary scan [binary format B64 [format %064d $bin]] I dec
return $dec
}
I tried using 64 for formatting and also tried LI to no avail. I read about "wide" but did not understand if it could be applied here.
P.S: I'm using tcl 8.4
Upvotes: 2
Views: 5970
Reputation: 137587
First off, the error is coming from format
, which isn't very happy with 64-bit numbers by default (for backward compatibility reasons) but we're really working with a string of characters there, so %064s
(s
, not d
) is a suitable fix.
You really ought to switch to using Tcl 8.5 where this is much easier:
binary scan [binary format B64 [format "%064s" $bin]] W dec
Or even just:
set dec [expr "0b$bin"]
In 8.4, you've got to do more work as the 64-bit support was a lot more primitive.
binary scan [binary format B64 [format %064s $bin]] II d1 d2
set dec [expr {wide($d1)<<32 | wide($d2)}]
That's slightly non-obvious, but the I
format is and always has been documented to work with 32-bit values only. So we stitch the two (big-endian) half-values back together after scanning.
Upvotes: 7