Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →
String#bit_get
static VALUE
rb_str_bit_get(int argc, VALUE *argv, VALUE str)
{
int bit = str_bit_get(argc, argv, str);
return bit < 0 ? Qnil : INT2FIX(bit);
}
Returns 0 or 1 for the bit at zero-based bit offset:
s = "\xAA" # 0b10101010 s.bit_get(0) # => 0 s.bit_get(1) # => 1
Returns nil if offset is beyond the end of self:
s.bit_get(8) # => nil
By default, bits within each byte are numbered from least-significant to most-significant. If lsb_first is false, byte order is unchanged but bits within each byte are numbered from most-significant to least-significant:
s.bit_get(0, lsb_first: false) # => 1 s.bit_get(1, lsb_first: false) # => 0
Raises IndexError if offset is negative. Raises ArgumentError if offset is too large to be represented. Raises ArgumentError if lsb_first is neither true nor false.
Ruby version changes
-
4.1
-
Basic bit operations are added.
String#bit_get,String#bit_set?,String#bit_set,String#bit_clear,String#bit_flipandString#bit_counthandle individual bits, andString#bitwise_not,String#bitwise_and,String#bitwise_or,String#bitwise_xor(with their!variants) handle whole strings. [Feature #22118]
-