Search code examples
perlhexdecimalpack

Convert Decimal to Hex and write to file in binmode in perl


Here is the piece of code. I am trying to write a hexadecimal to a file in binmode.

#!/usr/bin/perl
die "Usage: $0 infile outfile" unless scalar(@ARGV) > 1;
open(my $out, '>', $ARGV[1]) or die "cannot open in file: $!";
binmode($out);
$PrevlastByte = 116;
my $PrevlastByte = pack 'H*', $PrevlastByte;
print $out "$PrevlastByte";

$PrevlastByte is 116 and its equivalent hex is 74. When i see my outfile, I will have two bytes of data 11 and 60. I just want 1 byte of data in outfile i.e 0x74, when I see it in hex viewer. How can this be done. Please help.


Solution

  • You don't want hex. Hex is a string representation of a number. You want character 11610 aka character 7416.

    It is obtained using any of the following:

    chr(116)
    chr(0x74)
    pack('C', 116)
    pack('C', 0x74)
    "\x74"
    ...
    

    By the way, you should take advantage of STDOUT.

    #!/usr/bin/perl
    binmode STDOUT;
    my $PrevlastByte = 116;
    print pack 'C', $PrevlastByte;