but I got to thinking that, "Why do I need to pack the long integer 0x01020304 in the first place?" I thought I'd be able to do something like this:sub is_big_endian { my ($a,$b,$c,$d) = unpack("C4",pack("L",0x01020304)); ($a==0x01) && ($b==0x02) && return 1; #big endian ($a==0x04) && ($b==0x03) && return 0; #little endian }
Which didn't work, running via the debugger, I tried LOTS of variations attempting to make sense of what was actually going on:sub is_big_endian { $num=0x01020304; my ($a,$b,$c,$d) = unpack("C4",$num); ($a==0x01) && ($b==0x02) && return 1; #big endian ($a==0x04) && ($b==0x03) && return 0; #little endian }
Then I read that internally, all numbers are represented as double precision floats, so, I tried those as well:DB<1> c 242 main::is_big_endian(test-dns.pl:242): 242: my ($a,$b,$c,$d) = unpack("C4",0x01020304); DB<2> n main::is_big_endian(test-dns.pl:243): 243: ($a==0x01) && ($b==0x02) && return 1; #big endian DB<2> p $a 49 DB<3> p $b 54 DB<4> p $c 57 DB<5> p $d 48 DB<6> p unpack("C4",0x01020304) 49545748 DB<7> p unpack("L",0x01020304) 825637168 DB<12> $a=0x01020304 DB<13> p $a 16909060 DB<14> p unpack("CCCC",$a) 49545748 DB<15> p unpack("C4",$a) 49545748 DB<17> p unpack("C4",pack("L",($a))) 1234 [..stuff removed..] DB<51> p $a 16909060 DB<52> p unpack("b32",pack("L",$a)) 10000000010000001100000000100000 DB<55> p unpack("B32",pack("L",$a)) 00000001000000100000001100000100 DB<3> p unpack ("C*",x01020304) 1204849485048514852 DB<4> p unpack ("C*",0x01020304) 4954574857485448 DB<5> p unpack ("C*",0x00000001020304) 4954574857485448 DB<10> print join(" ", map { sprintf "%#02x", $_ } unpack("C*",pack( +"L",0x12345678))), "\n"; 0x12 0x34 0x56 0x78 DB<11> print join(" ", map { sprintf "%#02x", $_ } unpack("C*",0x123 +45678)), "\n"; 0x33 0x30 0x35 0x34 0x31 0x39 0x38 0x39 0x36
And those didn't match what I'd gotten before. So my question boils down to: "What is *actually* going on internally to give me the answer I get when doing an unpack("C",$a) where $a=0x01020304?"DB<15> print join(" ", map { sprintf "%#02x", $_ } unpack("C*",pack( +"D",$a))), "\n"; 0x41 0xb2 0x34 0x56 0x78 00 00 00 DB<16> print join(" ", map { sprintf "%#02x", $_ } unpack("C*",pack( +"D*",$a))), "\n"; 0x41 0xb2 0x34 0x56 0x78 00 00 00 DB<17> print join(" ", map { sprintf "%#02x", $_ } unpack("C*",pack( +"d*",$a))), "\n"; 0x41 0xb2 0x34 0x56 0x78 00 00 00 DB<18> print join(" ", map { sprintf "%#02x", $_ } unpack("C*",pack( +"d",$a))), "\n"; 0x41 0xb2 0x34 0x56 0x78 00 00 00
In reply to pack, unpack and internal represenation of numbers by 5mi11er
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |