Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert hex strings into numbers in Perl?

Tags:

hex

perl

I recently wrote a script which parsed a text representation of a single binary byte month field.

(Don't ask :-{ )

After fiddling with sprintf for a while I gave up and did this;

our %months = qw / x01 1         x02 2        x03 3         x04 4         x05 5         x06 6         x07 7         x08 8         x09 9         x0a 10         x0b 11         x0c 12 /; ... my $month = $months{$text}; 

Which I get away with, because I'm only using 12 numbers, but is there a better way of doing this?

like image 682
Chris Huang-Leaver Avatar asked Oct 07 '09 14:10

Chris Huang-Leaver


People also ask

How can I convert a hex string to an integer value?

To convert a hexadecimal string to a numberUse the ToInt32(String, Int32) method to convert the number expressed in base-16 to an integer. The first argument of the ToInt32(String, Int32) method is the string to convert. The second argument describes what base the number is expressed in; hexadecimal is base 16.

Does atoi convert hex?

The atoi() and atol() functions convert a character string containing decimal integer constants, but the strtol() and strtoul() functions can convert a character string containing a integer constant in octal, decimal, hexadecimal, or a base specified by the base parameter.

What is a string hexadecimal?

Hexadecimal Number String. The “Hexadecimal” or simply “Hex” numbering system uses the Base of 16 system and are a popular choice for representing long binary values because their format is quite compact and much easier to understand compared to the long binary strings of 1's and 0's.


2 Answers

If you have

$hex_string = "0x10"; 

you can use:

$hex_val = hex($hex_string); 

And you'll get: $hex_val == 16

hex doesn't require the "0x" at the beginning of the string. If it's missing it will still translate a hex string to a number.

You can also use oct to translate binary, octal or hex strings to numbers based on the prefix:

  • 0b - binary
  • 0 - octal
  • 0x - hex
like image 148
Nathan Fellman Avatar answered Sep 25 '22 04:09

Nathan Fellman


See hex and/or oct.

#!/usr/bin/perl  use strict; use warnings;  my @months = map hex, qw/x01 x02 x03 x04 x05 x06 x07 x08 x09 x0a x0b x0c/; print "$_\n" for @months; 
like image 31
Sinan Ünür Avatar answered Sep 22 '22 04:09

Sinan Ünür