1

I would like to extract date and time out of a binary file and convert it to ASCII in Perl. hex dump

How do I convert the binary data into an integer and into ASCII characters?

I have tried the code below, but it seems like I can only print out the first two bytes and then I only see zeroes for the next iterations. Occasionally, I do get other values, but it seems like I am not doing the conversion correct and missing some information.

 while (( $n = read FILE, $data, 4) != 0 ) {
  my $hex = sprintf('%04X', ord($data))

}

Is there some kind of conversion to integer that must take place? How do I convert this correctly?

Edit: In the hex dump I need to convert 04FF into an integer.

2 Answers 2

2

With the help of glebaty I was able to solve the problem. This is how I converted the 4 bytes into decimal values.

open FILE, "source.bin" or die $!;
while (( my $n = read $FILE, my $data, 4) != 0) {
  my $hex = unpack(  'H+', $data );
  my $decimal = hex($hex);
}
close FILE;
Sign up to request clarification or add additional context in comments.

Comments

1

ASCII is a 7-bit binary integer, so you need read by 1 byte from file, i think. Try this code:

open my $FILE, '<', 'file';                                                                                                                                   
while (( my $n = read $FILE, my $data, 1) != 0) {                                                                                                             
print chr(unpack('C', $data)). "\n";                                                                                                                  
}
close $FILE;

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.