in reply to Detecting machine Endian-ness

That is close to a test I've used:

my $o= pack( 'I', 0x04030201 ); if( substr($o,-4) eq "\04\03\02\01" ) { return "big"; } elsif( substr($o,0,4) eq "\01\02\03\04" ) { return "little"; } else { die "Strange endian"; }
Note that the "I" format can result in more than 4 bytes on some platforms.

        - tye (but my friends call me "Tye")

Replies are listed 'Best First'.
Re: (tye)Re: Detecting machine Endian-ness
by LunaticLeo (Scribe) on Aug 07, 2001 at 02:58 UTC
    Is substr() offset always in bytes?

    Note that the "I" format can result in more than 4 bytes on some platforms.

    Yeah, I suppose you could use 'L' then.

    I suppose you could figure out the size of integers with code like:

    @b = unpack('C*', pack('I', 0)); return scalar(@b);

    Then you could make the endian code more generic with:

    @b = unpack('C*', pack('I', 0)); $sizeof_long = scalar(@b); @c = (1..$sizeof_long); $i = pack('I', hex('0x0'.join('0',reverse @c))); $big = pack('C'.$sizeof_long, reverse @c); $lit = pack('C'.$sizeof_long, @); if ( substr($i, 0, $sizeof_long) eq $big ) { return 'big'; } elsif ( substr($i, 0, $sizeof_long) eq $lit ) { return 'little'; } else { return "strange"; }

      Good point. I don't do anything with "wide" strings in Perl yet so I usually forget to take that into consideration. But here we are making the strings so we know they'll be byte strings and we can use what I wrote or: length pack "I", 0 to find the number of bytes in an IV.

      I thought I had used a "native 32-bit integer" before for endianness testing, but for some reason couldn't think of "L". That certainly makes more sense than resorting to substr. (:

              - tye (but my friends call me "Tye")