我正在尝试将一些十进制数和二进制数相互转换。我正在使用以下格式生成的数据:
Example decimal: 163, Corresponding binary: 10100011
Binary table key:

...and the corresponding description for the binary number in question:

我希望能够获取十进制数,将其转换为二进制,然后使用此查找表打印给定小数的属性列表。我可以使用下面的代码将十进制转换为二进制:
sub dec2bin {
my $str = unpack("B32", pack("N", shift));
$str =~ s/^0+(?=\d)//; # otherwise you'll get leading zeros
return $str;
}但是不知道如何使用查找表。问题是,我有专门为这个表设计的二进制数字,比如1000011,10000011,101110011,但我就是看不到如何使用这些二进制数字来提取它们的描述。他们甚至有不同的长度!
有没有人能帮我弄明白这是怎么回事?
编辑:这是我找到的另一个查询表...也许这更准确/更有帮助?它看起来和我一模一样,但它来自该软件的官方website。

发布于 2013-06-18 01:12:54
更简单的方法可能是检查映射中的每个键,并将其直接与转换后的数字进行比较。
sub get_descriptions {
my $binary_num = shift;
my @descriptions;
for my $k (keys %description_map) {
# bitwise comparison
if( $k & $binary_num ) {
# add description because this bit is set
push @descriptions, $description_map{$k};
}
}
# full listing of all descriptions for the set bits
return @descriptions;
}发布于 2013-06-18 01:14:29
表格在基数16中,所以只需转换为基数2(我从另一个论坛复制/粘贴的表格,如果它与你的截图不同,请修复):
0000000001 the read is paired in sequencing
0000000010 the read is mapped in a proper pair
0000000100 the query sequence itself is unmapped
0000001000 the mate is unmapped
0000010000 strand of the query (1 for reverse)
0000100000 strand of the mate
0001000000 the read is the first read in a pair
0010000000 the read is the second read in a pair等等。
要以您的格式获得正确的描述,则应使用以下代码:
my @descriptions = (
"the read is paired in sequencing"
,"the read is mapped in a proper pair"
#...
);
check_number(163); # Note that you don't need to convert to binary :)
sub check_number {
my $number = shift;
my $bitmask = 1; # will keep incrementing it by *2 every time
for($i=0; $i < @descriptions; $i++) {
my $match = $bitmask & $number ? 1 : 0; # is the bit flipped on?
print "|$match| $descriptions[$i] | \n";
$bitmask *= 2; # or bit-shift - faster but less readable.
}
}我的测试代码的输出是(对不起,我得到了懒惰的复制/粘贴描述字符串,所以伪造了它们):
$ perl5.8 17152880.pl
|1| the read is paired in sequencing |
|1| the read is mapped in a proper pair |
|0| 3 |
|0| 4 |
|0| 5 |
|1| 6 |
|0| 7 |
|1| 8 |
|0| 9 |如果只想打印匹配的描述,请将循环中的print语句更改为print "$descriptions[$i]\n" if $match;
这种方法的好处是它很容易扩展到更长的描述表
https://stackoverflow.com/questions/17152880
复制相似问题