0
votes

I'm using arbitrary precision integers in TCL 8.6.

For example:

set x [expr {10**1000}]

How can I save this number to binary? The binary format command doesn't seem to work for this.

I also need to be able to read the number back in later.

I know I can use a loop doing x & 0XFFFF and x >> 16 to dump each word one at a time, but I thought maybe there an efficient was a way to dump the memory directly.

Any ideas?

2
Can you show your attempt using binary format pls.? - mrcalvin
By binary do you mean a string of 1 and 0 characters, or literal binary data that's not human readable? - Shawn
Are you trying to convert this to binary digits (0 and 1) or to actual binary data? - Donal Fellows

2 Answers

0
votes

How can I save this number to binary?

What about using format and scan, respectively?

scan [format %llb $x] %llb

As you are dealing with strings of characters, rather than strings of bytes, they are first choice.

0
votes

It depends on the serialization format you wish to use. And the code needing to read it again. And how fast it needs to be.

One method you could use is to write the number in ASN.1 BER encoding, which supports a binary integer of arbitrary length.

This can be done with tcllib packages math::bignum and ASN.1:

package require asn
package require math::bignum

set x [expr {10**100}]
set bindata [asn::asnBigInteger [::math::bignum::fromstr $x]]

As you can see from the procedure name fromstr, this isn't the fastest possible code.

If you wish to use some other serialization for integers you can invent different methods, like the looping and shifting as you already discovered.

The naive method of Tcl would be just to dump the string representation, but thats obviously less compact.