in reply to pack and unpack with 8 bit integers
The problem is that the i template needs at least 32 bits, but you're only giving it 8. The $size argument to bin2dec should be 32, but even then your function won't always work depending on the endianness of your system!
$ perl -wMstrict -le 'print unpack("B*",pack("i",3))' 00000011000000000000000000000000 $ perl -wMstrict -le 'print unpack("i",pack("B*", "00000011000000000000000000000000"))' 3 $ perl -wMstrict -le 'print unpack("i",pack("B*", "00000000000000000000000000000011"))' 50331648 $ perl -wMstrict -le 'print unpack("i",pack("B*","00000011")).""' Use of uninitialized value in concatenation (.) or string at -e line 1 +. $ perl -wMstrict -le 'print unpack("c",pack("B*","00000011"))' 3
(Note the use of "B*" instead of "B$size".) Some more general observations:
The i template is system-dependent. Unless the binary data itself is system-dependent, such as from C structs, I'd only use the system-independent formats, in this case for example the cCnNvV formats since those have a fixed size and endianness.
You say want to use i, but then only want handle 8 bits, that does not go together - why not use c to begin with? Also, you're not checking that your values will actually fit in 8 bits!
Lastly, I suspect you've got an XY Problem and you might want to explain to us what you're trying to accomplish overall. Don't worry about asking too many questions, but I would suggest you play around with pack and unpack a bit more, like I did above!
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: pack and unpack with 8 bit integers
by thanos1983 (Parson) on Sep 22, 2014 at 13:46 UTC | |
by Anonymous Monk on Sep 22, 2014 at 14:48 UTC | |
by thanos1983 (Parson) on Sep 22, 2014 at 21:57 UTC | |
by Anonymous Monk on Sep 22, 2014 at 23:01 UTC | |
by thanos1983 (Parson) on Sep 23, 2014 at 14:51 UTC |