Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine bitwise binary scores for a list of number in perl?

Tags:

binary

perl

I am trying to inter-convert some decimal and binary numbers. I am working with data produced in the following format:

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

I want to be able to take a decimal number, convert it to binary, and then use this look-up table to print a list of attributes for a given decimal. I'm able to convert my decimal to binary using this code:

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

But then don't see how to use the lookup table. The problem is, I have binary numbers specifically designed to be compatible for this table, such as 1000011, 10000011, 101110011, but I just don't see how to use these binaries to pull our their descriptions. They are even different lengths!

Can someone please help me understand what is going on here?

EDIT: here is another look-up table I found... perhaps this is more accurate/helpful? It looks identical to me, but is from the software's offiical website.

enter image description here

like image 460
jake9115 Avatar asked Nov 18 '25 17:11

jake9115


1 Answers

Once the number is converted, its base as expressed in the input is irrelevant. Internally, think of it as just a number.

The value 163 expresses a bitfield, that is, each of its bits is the answer to some yes-no question, and the table tells you how the questions are arranged.

You might give the bits human-readable names with subs, as in

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

Then decoding the bitfield resembles

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";

Output:

read is paired?  YES
read is mapped?  YES
strand of mate = 1
read is second?  YES
like image 177
Greg Bacon Avatar answered Nov 21 '25 10:11

Greg Bacon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!