Hey all,
I ran into a situation recently where I was reading from an I2C device, and the byte ordering was in the opposite endianness that I was expecting. Although I fixed the problem by reversing the bytes before returning them, I went off to research exactly what endian was. I've spent numerous hours testing, reading and more testing, but I still can't grasp it fully. I'm hoping just one or two more examples will have it 'click'.
So, I'll start off with a couple of examples here to see if I have the basics down. Please feel free to elaborate with other examples or comments etc.
Set up our number, and two byte scalars (full version copy/pastable at the bottom of the post):
use warnings; use strict; use feature 'say'; my $num = 1023; # 0x03ff my ($b1, $b2);
Now, if I do the following bit shifting, the printf() is printing the bytes in big endian format, correct?
$b1 = ($num & 0xff00) >> 8; $b2 = $num & 0xff; printf("%x, %x\n", $b1, $b2); # 3, ff
Likewise, if I reverse the operations/bytes, this one will print in little endian format, right?
$b1 = $num & 0xff; $b2 = ($num & 0xff00) >> 8; printf("%x, %x\n", $b1, $b2); # ff, 3
Full code:
use warnings; use strict; use feature 'say'; my $num = 1023; my ($b1, $b2); $b1 = ($num & 0xff00) >> 8; $b2 = $num & 0xff; printf("%x, %x\n", $b1, $b2); $b1 = $num & 0xff; $b2 = ($num & 0xff00) >> 8; printf("%x, %x\n", $b1, $b2);
In reply to Understanding endianness of a number by stevieb
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |