Re: packing a C structure
- From: "jl_post@xxxxxxxxxxx" <jl_post@xxxxxxxxxxx>
- Date: Tue, 30 Oct 2007 09:22:32 -0700
On Oct 30, 4:19 am, rams <haai...@xxxxxxxxx> wrote:
Thanks a lot for your response.The pack command you provided gave me
much needed output.I got this almost done.
You're very welcome. I'm glad I could help.
The only problem right now
iam facing is to convert a variable into a 6 byte hexa value.
i have variable $i=123456789012 then i would like to convert this into
a hexa value 12 34 56 78 90 12
and i would like this hexa value also to pack along with my
structure..
Okay, before you do this, you must realize that $i (or
123456789012) should be a string (surrounded by quotes) and NOT a
number -- otherwise, any leading zeroes (or letters A-F) you had in
your number could be lost or misinterpreted.
So if you had a line like:
my $i = "123456789012"; # notice the "" marks
and you wanted a string with the bytes 12 34 56 78 90 12
(hexadecimal), you should use the "H*" pack-string, like this:
my $string = pack('H*', $i);
Now $string is equal to "\x{12}\x{34}\x{56}\x{78}\x{90}\x{12}".
You can do this to prove it to yourself (remember to use "eq" (and not
"==") when comparing strings) with the following code:
if ($string eq "\x{12}\x{34}\x{56}\x{78}\x{90}\x{12}")
{
print "The strings are equal!\n"
}
The "H*" pack template tells pack() to interpret the variable it
packs as the hexadecimal values of the bytes the final (packed) string
will have.
If that's a confusing explanation for you, consider this unpack()
line:
$i = unpack('H*', $string);
This line reads the $string and returns another string which contains
the $string's values in hexadecimal form. The pack() example,
naturally, does the exact opposite.
If you want (or need) a quick way to check the $string contents
(for debugging purposes), you can use this line of code:
printf "0x%x\n", ord($_) foreach split(//, $string);
This will print out each character's hexadecimal value, one character
at a time. In fact, if $string is indeed what you wanted (that is,
made up of bytes 12 34 56 78 90 12 (hexadecimal)), then this line of
code should give you the following output:
0x12
0x34
0x56
0x78
0x90
0x12
I hope this helps, Rams.
Take care and God bless.
-- Jean-Luc Romano
.
- References:
- packing a C structure
- From: haairam
- Re: packing a C structure
- From: jl_post@xxxxxxxxxxx
- Re: packing a C structure
- From: rams
- Re: packing a C structure
- From: jl_post@xxxxxxxxxxx
- Re: packing a C structure
- From: rams
- packing a C structure
- Prev by Date: Perl and modifying a PDF document
- Next by Date: Re: sockets problem
- Previous by thread: Re: packing a C structure
- Next by thread: Re: packing a C structure
- Index(es):
Relevant Pages
|