For example:
I have $a= -1
. If I print it using printf
with %.4b
or %b
, it gives me 32-bit
all 1's.
But, I only want to print the least significant 4 bits like 1111
in the file in binary.
Any ideas how to do it?
Thanks
-1
in binary is represented via 2s complement, so it is all 1
s. (See here for more: What is “2's Complement”?)
If you want to 'limit' it, then the way you can do this is with a bitwise and
.
Switching on 4 bits is
1+2+4+8 = 15.
Therefore:
use strict;
use warnings;
my $val = -1;
printf ( "%b", $val & 15 );
%.4b
refers to fractional digits, %04b
formats to at least 4 digits, padding leading 0
s as needed.
To cater for negative integers, take the modulus by 16 ( 2^<number of least significant bits>
).
my @b = (12, 59, -1, 1 ); # sample of integers
@b = map { $_ % 16; } @b; # take modulus
printf ("4-bits: %04b" . (", %04b" x $#b) . ";\n", @b );
# output with computed number of placeholders