in reply to array of binaries to hex conversion

#!/usr/bin/perl -- use strict; use warnings; use Data::Dump; my @rand1 = qw( 0 1 0 1 0 1 0 1 0 1 1 1 0 1 1 0 0 0 1 ); my $bin = arraystring (@rand1); my $dec = stringdecimal($bin); my $hex = sprintf("0x%x", $dec); my $ex = b32hex(@rand1); dd \@rand1, $bin, $dec, $hex, $ex; sub stringdecimal { return unpack("N", pack("B32", substr("0" x 32 . shift, -32))); } sub arraystring { my $string = join('', @_); return $string; } sub b32hex { '0x'. unpack 'H*', pack("B32", substr("0" x 32 . join('',@_), -32) +) } __END__ ( [0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1], "0101010101110110001", 175025, "0x2abb1", "0x0002abb1", )

Replies are listed 'Best First'.
Re^2: array of binaries to hex conversion
by remiah (Hermit) on Sep 12, 2012 at 02:12 UTC

    Hello.

    I would like to ask you a question. The result will differ by byte orders.

    my $tmp=pack("B32", substr("0" x 32 . join('',@rand1), -32)); #this prints 'as 32bit big endian:0x2abb1' printf "as 32bit big endian:0x%x\n", unpack('N',$tmp) ; #this prints 'as 32bit little endian:0x200' printf "as 32bit little endian:0x%x\n", unpack('S',$tmp) ;
    There is "<" for little endian, and ">" for big endian, which pack,unpack offers. OP treats it as "N"=32bit int, big endian, so I would like to do like this.
    pack("B>32", $bitstring);
    pack("(B32)>*",$bitstring);
    
    But both of them doesn't work...
    How can I add endian specification with your one line conversion? Is there a good way?