Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →
String#bit_flip
static VALUE
rb_str_bit_flip(int argc, VALUE *argv, VALUE str)
{
return str_mutate_bit(argc, argv, str, STR_BIT_FLIP);
}
Flips the bit at zero-based bit offset; returns self:
s = "\x00" s.bit_flip(1) # => "\x02" s.bit_flip(1) # => "\x00"
With length, flips the length consecutive bits beginning at offset; with a Range, flips the bits covered by range:
s = "\x00\xFF" s.bit_flip(4, 8) # => "\xF0\xF0" s = "\x00\xFF" s.bit_flip(4..11) # => "\xF0\xF0"
The entire region must lie within self; a region that extends beyond the end raises IndexError rather than being clamped. Writing zero bits is a no-op, but even an empty region raises IndexError when it begins beyond the end of self.
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 = "\x00" s.bit_flip(1, lsb_first: false) # => "\x40" s = "\x00\xFF" s.bit_flip(4, 8, lsb_first: false) # => "\x0F\x0F"
Raises IndexError if offset is out of range, or if any part of the region lies outside self. Raises ArgumentError if length is negative. Raises ArgumentError if a bit position is too large to be represented. Raises ArgumentError if lsb_first is neither true nor false. Raises FrozenError if self is frozen, even when writing zero bits.
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]
-