Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create byte array in tcl

Tags:

tcl

I want to do something like this---

byte[] byte2 = new byte[19];

how can I do same thing in tcl ?

like image 614
Anjali Avatar asked Feb 16 '26 01:02

Anjali


2 Answers

Tcl handles arrays of bytes as if they were strings that only contained the characters from U+0000 to U+00FF (i.e., as if they were ISO 8859-1 characters). There are some details in the implementation (they're transported around Tcl's innards as byte arrays, not as full Unicode strings or some horrible pseudo-UTF-8 byte sequence) but you just treat them as strings.

To make a string of NUL bytes that is 19 bytes long, you do:

set byte2 [string repeat "\u0000" 19]

Then you can use the binary command to operate on it (or encoding convertfrom to reinterpret it as a string in some other encoding). You really should not care about whether it is bytes or characters or whatever in your scripts. In particular, Tcl has lots of commands that operate on strings just fine, and they work just as well on byte arrays.

The only point where it really matters whether it is really an array of bytes is when you are working in the C API. At that point, if you need to read the byte array you use Tcl_GetByteArrayFromObj to obtain a real array of bytes (unsigned char in C) though you shouldn't modify that array of bytes if you didn't create it or, rather more technically, if the reference count on the Tcl_Obj is greater than 1 (i.e., if Tcl_IsShared returns a true value; if it is, you duplicate with Tcl_DuplicateObj to get something you can modify though you then have to ensure it is stored or deallocated correctly).

like image 84
Donal Fellows Avatar answered Feb 20 '26 00:02

Donal Fellows


I want to further clarify on what Donal wrote.

The point, that in Tcl one operates on byte arrays mostly like on strings, should be stressed. I mean, the code

byte[] byte2 = new byte[19];

hints the OP would then want to access elements of that byte2 C-style array randomly, replacing them with new values etc.

In contrast, such things in Tcl work differently. If one wants to have an indexed almost-C-style array, one should use lists instead, and only convert the resulting list to a real byte string (using the binary format command) when [s]he is about to serialize the data to a wire format (or write to a file or whatever). Another approach is handy when the resulting byte array is being formed incrementally, by appending values one by one; in this case one should simply use binary format and append.

I would urge the OP to look at some of the modules from tcllib dealing with binary encodings (base64 is one obvious candidate).

like image 41
kostix Avatar answered Feb 20 '26 02:02

kostix