Perl: How do I extract certain bits from a byte and then covert these bits to a hex value?

Posted by Siegfried Hepp on Stack Overflow See other posts from Stack Overflow or by Siegfried Hepp
Published on 2012-11-24T16:39:53Z Indexed on 2012/11/24 17:04 UTC
Read the original article Hit count: 194

I need to extract certain bits of a byte and covert the extract bits back to a hex value.

Example (the value of the byte is 0xD2) :

76543210 bit position
11010010 is 0xD2
  • Bit 0-3 defines the channel which is 0010b is 0x2
  • Bit 4-5 defines the controller which is 01b is 0x1
  • Bit 6-7 defines the port which is 11b is 0x3

I somehow need to get from the byte is 0xD2 to channel is 0x2, controller is 0x1, port is 0x3

I googled allot and found the functions pack/unpack, vec and sprintf. But I'm scratching by head how to use the functions to achieve this. Any idea how to achieve this in Perl ?

© Stack Overflow or respective owner

Related posts about perl

Related posts about bitmap