velpandian
velpandian

Reputation: 471

How to handle long integers in TCL with binary format command?

% binary scan [ binary format i* 146366987889541120] B* g
integer value too large to represent

Can anyone help me in computing a long integer value using binary format commnand . But we are getting error and there is no way of representing 'l' in the syntax (like in the format command format %lx 146366987889541120).

% format %lx  146366987889541120
208000000000000
%
%
% format %x  146366987889541120
0
%

Can anyone sugggest me a way to solve this ?

Upvotes: 1

Views: 2360

Answers (1)

Johannes Kuhn
Johannes Kuhn

Reputation: 15163

Edit: Just use

format %llb 146366987889541120

If you want a binary string representing this number.


If you don't deal with wide integer (bigger than 64-bit, added with Tcl 8.5), you can use

binary scan [ binary format w 146366987889541120] B* g

But if you have longer integers, the best workarround that I found is:

# convert a binary string to a large integer
binary scan $bytes H* temp
set num [format %lli 0x$temp]
# convert a number to a binary string.
set bytes [binary format H* [format %llx $num]]

This has some bugs (leading zero), so you want to add a 0 for binary format.

set hex [format %llx $num]
if {[string length $hex]%2} {set hex 0$hex}
set bytes [binary format H* $hex]

But I doubt that this approach yields the best performance.

Upvotes: 1

Related Questions