0

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

Will
  • 6,561
  • 3
  • 30
  • 41
x xb
  • 3
  • 1

2 Answers2

0

-1 in binary is represented via 2s complement, so it is all 1s. (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 );
Community
  • 1
  • 1
Sobrique
  • 52,974
  • 7
  • 60
  • 101
0

%.4b refers to fractional digits, %04b formats to at least 4 digits, padding leading 0s 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
collapsar
  • 17,010
  • 4
  • 35
  • 61