Domanda

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.

È stato utile?

Soluzione

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;

Altri suggerimenti

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;
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top