如何使用二进制格式命令处理TCL中的长整数?

时间:2013-10-21 09:30:26

标签: tcl

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

任何人都可以帮助我使用二进制格式commnand计算长整数值。  但是我们遇到了错误,并且没有办法在语法中表示'l'(比如格式化命令format %lx 146366987889541120)。

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

有人能告诉我解决这个问题的方法吗?

1 个答案:

答案 0 :(得分:1)

修改:只需使用

即可
format %llb 146366987889541120

如果你想要一个代表这个数字的二进制字符串。

<小时/> 如果你不处理宽整数(大于64位,加上Tcl 8.5),你可以使用

binary scan [ binary format w 146366987889541120] B* g

但是如果你有更长的整数,那么我找到的最好的工作方式是:

# 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]]

这有一些错误(前导零),所以你想为binary format添加一个0。

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

但我怀疑这种方法会产生最佳效果。