4

I want to be able to output 0x41, and have it show up as A.

This is what I have tried so far:

my $out;
open $out, ">file.txt" or die $!;
binmode $out;
print $out 0x41;
close $out;

It outputs 65 instead of A in the resulting file. This is not what I want.

I also have read this similar question, but I wouldn't transfer the answer over. pack a short results to 2 bytes instead of 1 byte.

1
  • I think the most important hint in the perldoc of print is: Prints a string or a list of strings. ... and not numbers. That's why the binary mode of the file handle (although needed for binary data!) is a red herring regarding the binary interpretation. I have also fallen into this trap. Commented Jun 20, 2022 at 10:52

3 Answers 3

3

You can use chr(0x41).

For larger structures, you can use pack:

pack('c3', 0x41, 0x42, 0x43) # gives "ABC"

Regarding your suspicion of pack, do go read its page - it is extremely versatile. 'c' packs a single byte, 's' (as seen in that question) will pack a two-byte word.

Sign up to request clarification or add additional context in comments.

2 Comments

AFAIK, chr will work for any byte value (0-255). It has a bit more complex relationship to Unicode. Still, pack is quite reliable, as you can tailor the template to what you need.
consider to use pack('C', ...). Otherwise for values above 0x7f there is a warning "Character in 'c' format wrapped in pack" (although the output is correct).
1

Use the chr function:

print $out chr 0x41

Comments

1

pack need two argument: The first argument explain how and how many data have to be packed:

perl -e 'printf "|%s|\n",pack("c",0x41,0x42,0x44);'
|A|

perl -e 'printf "|%s|\n",pack("c3",0x41,0x42,0x44);'
|ABD|

perl -e 'my @bytes=(0x41,0x42,0x43,0x48..0x54);
         printf "|%s|\n",pack("c".(1+$#bytes),@bytes);'
|ABCHIJKLMNOPQRST|

you could even mix format in the 1st part:

perl -e 'printf "|%s|\n",pack("c3B8",0x41,0x42,0x44,"01000001");'
|ABDA|

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.