Hi PerlMonks.. =)
I have a 4 byte hex string and I want to get a decimal number out of it that is bit packed N bits long and at M bits offset.
For example...
Hex : 1c023d64
Assume the left is the MSB and right is the LSB (bits 1->32).
I want to compose a decimal number using bits 23-27 so thats N = 23 and M = 5.
So if I convert the above hex to binary...
Bin : 000111000000001000111101011001100
now the bit sequence i want is...
01011
and then convert this to decimal would give decimal number 11.
Now whats the nicest way to do this automatically? My string manipulation skills are less than 1337 so I was doing this a rather painful way...
sub Hex2Bin {
$hex = $_[0];
%h2b = ( 0 => "0000", 1 => "0001", 2 => "0010", 3 => "0011",
4 => "0100", 5 => "0101", 6 => "0110", 7 => "0111",
+
8 => "1000", 9 => "1001", a => "1010", b => "1011",
c => "1100", d => "1101", e => "1110", f => "1111");
(my $binary = $hex) =~ s/(.)/$h2b{lc $1}/g;
return $binary;
}
This would convert the hex to a binary string and from there I was going to extract the bits and then recompose the binary.
I'm sure there is some slick commands around that will let me do this quickly...? Any help would be appreciated.
For the curious I'm trying to pull out channel status information that's bit packed for GPS satellite logs I'm playing with.
Regards Paul.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.