Perl Bit Operations

I have an attribute (32 bits long), each bit corresponds to a certain functionality. Perl script I write should include the 4th bit, but keep the previous definitions of the other bits.

I use in my program:

Sub BitOperationOnAttr { my $a=""; MyGetFunc( $a); $a |= 0x00000008; MySetFunc( $a); } 

** MyGetFunc / MySetFunc are my own functions that know the meaning of read / fix.

Questions:

  • if using $a |= 0x00000008; right?

  • how to extract a hexadecimal value from a regular expression from line I: For example:

"Attribute: Somestring: value (8 long (0x8))"

+4
source share
2 answers
  • when using $ a | = 0x00000008; Right?

Yes, it is normal.

  • how to extract a hexadecimal value from a regular expression from a string that I have: For example:

"Attribute: Somestring: value (8 long (0x8))"

I assume that you have a line similar to the one above and you want to use the regex to extract "0x8". In this case, something like:

 if ($string =~ m/0x([0-9a-fA-F]+)/) { $value = hex($1); } else { # string didn't match } 

must work.

+5
source

Perl provides several ways to process binary data:

  • Bitwise Operators & , | and ~ .
  • The functions pack and unpack .
  • vec function

Your script sounds like a set of packed flags. Bitwise operators are suitable for this:

 my $mask = 1 << 3; # 0x0008 $value |= $mask; # set bit $value &= ~$mask; # clear bit if ($value & $mask) # check bit 

vec is for use with bit vectors. (Each element has the same size, which should have a strength of two.) It can also work here:

 vec($value, 3, 1) = 1; # set bit vec($value, 3, 1) = 0; # clear bit if (vec($value, 3, 1)) # check bit 

pack and unpack better suited to working with things like C structs or endianness.

+23
source

Source: https://habr.com/ru/post/1335261/


All Articles