Results 1 to 7 of 7
  1. #1
    Join Date
    Jun 2004
    Posts
    4

    Unanswered: arrays into scalar

    Hi,

    I have an array of binary numbers and I'd like to convert that into hex. I know how to do it using the scalar format, but not with any array.

    thanks

  2. #2
    Join Date
    Feb 2004
    Location
    In front of the computer
    Posts
    15,579
    Provided Answers: 54
    You can reference array items something like:
    Code:
    my @a, $line;
    @a = <>;
    $line = $a[6];
    print reverse($line); # print just line 7 backwards
    -PatP

  3. #3
    Join Date
    Jun 2004
    Posts
    4

    array of binary into array of hex

    Thanks Pat,

    I know how to reference an array, but for example:
    Have:
    @array = 0 1 0 0 1 0 1 0;
    Need:
    @array = 4A

    I don't know how to use the built in functions for hex and binary because I need 4 elements of the array at a time to convert.

  4. #4
    Join Date
    Feb 2004
    Location
    In front of the computer
    Posts
    15,579
    Provided Answers: 54
    There is probably a quicker way, but you could use:
    Code:
    #  ptp  20040607  Repackage array of bool as a variable
    
    my @a, $val;
    
    @a = (0, 1, 0, 0, 1, 0, 1, 0);
    
    $val = 0;
    foreach my $i (@a) { $val = 2 * $val + $i };
    
    print "The value is: $val\n\n";
    -PatP

  5. #5
    Join Date
    Jan 2004
    Location
    Germany
    Posts
    167
    Quote Originally Posted by Dittocat15
    Hi,

    I have an array of binary numbers and I'd like to convert that into hex. I know how to do it using the scalar format, but not with any array.

    thanks
    To get a scalar of the array you can use join (join("",@array)) and the you can convert the scalar!
    board.perl-community.de - The German Perl-Community

  6. #6
    Join Date
    Jun 2004
    Location
    Nowhere Near You
    Posts
    89
    Code:
    my(@a) = (1, 1, 1, 1, 1, 1, 1, 0);
    $a=sprintf "%10lx",oct("0b".join('',@a));
    #print $a;

  7. #7
    Join Date
    Jun 2004
    Location
    Nowhere Near You
    Posts
    89
    Of course if your "binary string" is really long ...

    Code:
    #!\user\bin\perl -w
    
    my(@a)=(1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0);
    print BinToHex(\@a),"\n";
    
      sub BinToHex{
        my(%h)=('1000'=>'1','0100'=>'2','1100'=>'3','0010'=>'4','1010'=>'5','0110'=>'6','1110'=>'7','0001'=>'8','1001'=>'9','0101'=>'A','1101'=>'B','0011'=>'C','1011'=>'D','0111'=>'E','1111'=>'F'
                ,'1'=>'1',   '01'=>'2', '11'=>'3',  '001'=>'4', '101'=>'5', '011'=>'6', '111'=>'7');
        $_=reverse join('',@{$_[0]});
        s/([01]{1,4})/$h{$1}/g;
        return scalar reverse;
         };

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •