perl - 如何确定 perl 中数字列表的按位二进制分数?

标签 perl binary

我正在尝试相互转换一些十进制数和二进制数。我正在处理以下列格式生成的数据:

Example decimal: 163,   Corresponding binary: 10100011

Binary table key:

enter image description here

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

enter image description here

我希望能够获取十进制数,将其转换为二进制,然后使用此查找表打印给定十进制的属性列表。我可以使用以下代码将我的十进制转换为二进制:

sub dec2bin {
    my $str = unpack("B32", pack("N", shift));
    $str =~ s/^0+(?=\d)//;   # otherwise you'll get leading zeros
    return $str;
}

但是后来不知道怎么用lookup table。问题是,我有专为与该表兼容而设计的二进制数,例如 1000011、10000011、101110011,但我只是不知道如何使用这些二进制数来提取它们的描述。它们的长度甚至不同!

有人可以帮我理解这里发生了什么吗?

编辑:这是我找到的另一个查找表……也许这更准确/更有帮助?它看起来和我一模一样,但来自软件的官方 website .

enter image description here

最佳答案

一旦数字被转换,它在输入中表示的基数就无关紧要了。在内部,将其视为一个数字。

值 163 表示一个位域,即它的每一位都是一些是非问题的答案,表格告诉你这些问题是如何排列的。

您可以使用 subs 为这些位赋予人类可读的名称,如

sub read_is_paired { $_[0] & 0x0001 }
sub read_is_mapped { $_[0] & 0x0002 }
sub strand_of_mate { $_[0] & 0x0020 }
sub read_is_2nd    { $_[0] & 0x0080 }

然后解码位域类似于

my $flags = 163;
print "read is paired?  ", read_is_paired($flags) ? "YES" : "NO", "\n",
      "read is mapped?  ", read_is_mapped($flags) ? "YES" : "NO", "\n",
      "strand of mate = ", strand_of_mate($flags) ? "1"   : "0",  "\n",
      "read is second?  ", read_is_2nd($flags)    ? "YES" : "NO", "\n";

输出:

read is paired?  YES
read is mapped?  YES
strand of mate = 1
read is second?  YES

关于perl - 如何确定 perl 中数字列表的按位二进制分数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17152880/

相关文章:

regex - 有没有办法让 Perl 正则表达式搜索不区分大小写?

perl - 在 conda 安装的程序中无法在 @INC 中找到 File/Slurp.pm

c++ - 将长度恰好为8的倍数的 '1'和 '0'字符串转换为一定字节数

mysql - 在 MySQL 中存储 BINARY 的优点

套接字上下文中的 Java 和二进制数据

java - 将输出消息从 java 控制台重定向到 jTextArea 或 jLabel

perl - 使用与父脚本相同的 @INC 调用脚本

perl - 使用 "strict subs"时不允许使用裸字

c++ - 序列化二进制结构 gcc vs cl

c++ - 如何克服 Bitset 错误