Reputation: 99
I want to convert the hex values lying in $1, $2, $3, and $4 to binary and save in an array. I know $1 is only a string, so I tried to convert it to hex before converting to binary, but it doesn't work... Here's my code:
#! usr/bin/perl
use warnings;
use strict;
while(<>)
{
if(/SIB_DBG/)
{
if(/TTRB:\s*([\da-f]+)\s([\da-f]+)\s([\da-f]+)\s([\da-f]+)/ ||
/ETRB:\s*([\da-f]+)\s([\da-f]+)\s([\da-f]+)\s([\da-f]+)/ ||
/Command\sETRB\s*([\da-f]+)\s([\da-f]+)\s([\da-f]+)\s([\da-f]+)/ )
{
my $one = $1;
my $two = $2;
my $three = $3;
my $four = $4;
print "$_ $one $two $three $four\n";
printf("binary :%b\n",$four);
}
}
}
My input logfile is like
Aug 31 15:25:53 usb3 kernel: [ 78.812034] SIB_DBG TTRB:01000680 00080000 00000008 00030840, PTR: ffff88005ff8b800
Aug 31 15:25:53 usb3 kernel: [ 78.815428] SIB_DBG ETRB: 5ff8b850 00000000 01000000 01018001
Also I get an error saying in some of the lines..
Argument "f8891" isn't numeric in printf at script.plx line 21, <> line 6.
Upvotes: 2
Views: 15515
Reputation: 53478
The problem is there's a difference between a text string and a numeric value.
The latter can be represented as hexidecimal, binary, octal - behind the scenes, the computer is thinking in binary anyway.
A text string though, is a sequence of character codes that represent symbols from a character set.
So to do what you want - you need to convert your 'string' to a numeric value first.
Perl has the hex
function to do this for you:
#!/usr/bin/env perl
use strict;
use warnings;
my $string = '5ff8b850';
my $value = hex ( $string );
print "Dec: ",$value,"\n";
printf ( "Hex: %X\n", $value );
printf ( "Binary: %b\n", $value );
Upvotes: 5