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?
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];
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);
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.
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.
You can use the pack
function for this.
Example:
$ perl -e 'print pack("H*", "303132616263"), "\n";'
012abc
Check out the pack tutorial.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With