Perl :Create binary number and convert it into hex -
i want create binary number given user input. input - array of number output - binary number
binary number should created such have 1 on places has been given input.
in given case input 1, 3, 7 binary no should 1000101 has 1's on 1, 3 , 7 places left.
@x = [ 1, 3, 7 ]; $z = 0; for( $i = 0; $i < 10; $i++ ){ foreach $elem ( @x ){ if( $elem == $i ){ join( "", $z, 1 ); } else{ join( "", $z, 0 ); } } } print "value of z: $z"; after execution, getting value of z 0.
i need convert binary hexadecimal.
is there function converts binary hexadecimal?
[ ] creates array , returns reference array, assigning single scalar (poorly named) @x.
you misusing join. use use strict; use warnings qw( );! have caught error.
fixed:
my @bits = ( 1, 3, 7 ); $num = 0; $num |= 1 << $_ @bits; # 76543210 printf("0b%b\n", $num); # 0b10001010 printf("0x%x\n", $num); # 0x8a it seems want 0b1000101, need correct indexes.
my @bits_plus_1 = ( 1, 3, 7 ); $num = 0; $num |= 1 << ( $_ - 1 ) @bits_plus_1; # 6543210 printf("0b%b\n", $num); # 0b1000101 printf("0x%x\n", $num); # 0x45
Comments
Post a Comment