suve

awful: function: extract-bits

Available since rev.40 (v.0.5.4).

Declaration

bin :extract-bits ( mixed $VALUE , int $LO , int $HI )

Summary

Extracts bits from the provided value, starting at $LO lowest bit and going towards the $HI lowest bit. Both bounds are included in the resulting value. If the bounds span across more than 64bits, the bits closer to the higher bound will be returned.

Endianness is taken into account when moving across bytes. Extracting the 0th bit from an int value should yield the same result as taking modulo 2.

Note that this function was intended to be used primarily with integers, so its behaviour with other types may be confusing.

  • For integers, the values are numeric, so behaviour should be obvious.
  • For floats, the values are not converted to ints; instead, bits are taken straight out of the IEEE Float representation.
  • For ASCII strings, the values are not converted. Bits are taken out of the string's characters, with the leftmost characters treated as containing most significant bits. (In string asdf, the f is considered bits 0-7.)
  • For NILs, always returns 0.
  • For all other types (including UTF-8 strings), bits are taken straight out of the memory representation of the underlying interpreter object. This will most likely yield totally useless, if not amusing, data.

Example

# :extract-bits example
:set &num i0
 
:write s'Gibe number plox: '
:read &num
 
# Default print omits leading zeros
:writeln s'binary: ' :set b0 $num
 
# Print every single bit in loop, including leading zeros
:write s'  bits: '
:set &idx i63
!while :ge $idx i0
   :write :extract-bits $num $idx $idx
   :sub &idx i1
!done
:writeln

wikipage modified on 2014/0916/2155