Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a hex-encoded string to a byte string in Perl?

Tags:

hex

perl

packet

My original code is in Python, but I need to convert it to Perl for some libraries that I don't have at my disposal in Python.

In Python I would do this:

packet=binascii.unhexlify('F0000000F6905C452001A8C0000000000160994E810FB54E0100DB0000000000000')

AND

This would create a string containing the binary representation of:

0xF0 0x00 0x00 0x00 0xF6 0x90 0x5C 0x45 etc...

Now that my string is a byte array I can send it as the payload for my packet. How do I do it Perl?

like image 456
Nowayz Avatar asked Oct 16 '11 08:10

Nowayz


People also ask

How do you convert hex to bytes?

To convert hex string to byte array, you need to first get the length of the given string and include it while creating a new byte array. byte[] val = new byte[str. length() / 2];

How do you convert a hex string to a byte array?

To obtain a string in hexadecimal format from this array, we simply need to call the ToString method on the BitConverter class. As input we need to pass our byte array and, as output, we get the hexadecimal string representing it. string hexString = BitConverter. ToString(byteArray);

Is hex same as byte?

Each Hexadecimal character represents 4 bits (0 - 15 decimal) which is called a nibble (a small byte - honest!). A byte (or octet) is 8 bits so is always represented by 2 Hex characters in the range 00 to FF.

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.


1 Answers

You can use the pack function for this.

Example:

$ perl -e 'print pack("H*", "303132616263"), "\n";'
012abc

Check out the pack tutorial.

like image 167
Mat Avatar answered Oct 19 '22 01:10

Mat