右移二进制no并获取变量中的移位位

时间:2019-03-26 10:00:10

标签: perl

我有一个二进制的不发言权,我有一个变量,说值= 4。 我想按“值”变量中存储的位数无二进制数的右移,然后想将移位后的位数存储在变量中,并且还想将右移后的二进制数保存在另一个变量中

示例:

binary_number = 110000001
value =4 
then shifting no of bits in "value" to right (11000001 >> value)

现在我要最终拥有两个变量,一个变量包含移位后的二进制数,另一个变量具有移位的位。

对于上面的示例,我想要的解决方案是

right_shifted_binary = 11000
bits_shifted = 0001

我找不到适合该问题的文档,因为大多数问题都在讲述算术右移。

1 个答案:

答案 0 :(得分:1)

基于$value生成位掩码,并使用AND(&)运算符:

#!/usr/bin/perl
use warnings;
use strict;

my $binary = 0b110000001;
my $value  = 4;

# create mask with $value left-most bits 1
my $mask = ~(~0 << $value);

print "INPUT:     ", unpack("B*", pack("N", $binary)), " ($binary)\n";

# right shift by $value bits
my $right_shifted_binary = $binary >> $value;
print "RIGHT:     ", unpack("B*", pack("N", $right_shifted_binary)), " ($right_shifted_binary)\n";

# extract "remainder" of shift using mask
my $bits_shifted = $binary & $mask;
print "REMAINDER: ", unpack("B*", pack("N", $bits_shifted)), " ($bits_shifted)\n";

exit 0;

试运行:

$ perl dummy.pl
INPUT:     00000000000000000000000110000001 (385)
RIGHT:     00000000000000000000000000011000 (24)
REMAINDER: 00000000000000000000000000000001 (1)

# Proof
$ echo "24 * 16 + 1" | bc
385

如果二进制数以字符串形式给出,则可以先将其转换为整数:

my $binary_string = "110000001";
my $binary = unpack("N", pack("B32", substr("0" x 32 . $binary_string, -32)));

但是,如果已经是一个字符串,那么解决方案会更简单:

#!/usr/bin/perl
use warnings;
use strict;

my $binary_string = "110000001";
my $value  = 4;

print "INPUT:     $binary_string\n";
print "RIGHT:     ", substr($binary_string, 0, -$value), "\n";
print "REMAINDER: ", substr($binary_string, -$value),    "\n";

exit 0:
$ perl dummy.pl
INPUT:     110000001
RIGHT:     11000
REMAINDER: 0001