From: Dossy Date: 2002-12-31T23:04:03+09:00 Subject: Re: How to do bitwise ops on a byte? On 2002.12.31, Bernard Miller wrote: > I can?t seem to find a way to do bitwise ops on a > byte, at least using the standard library. [...] I was just doing bitwise ops last night. What are you trying to do? > As a side note, I find a lot of the unpack functions > to be just weird. I don?t understand what ?B? and ?b? > are good for. They extract bits but return an array > with 1 element that is a string containing the > characters ?1? and ?0?, but those are not really bits, > and are not useful for bitwise operations. The "b" and "B" operators simply return string representations in base 2. 123.chr.unpack("B8") # => ["01111011"] Take the value 123 and return the 8-bit string representation of it in binary, which is 01111011. Alternatively: sprintf "%8b", 123 # => "01111011" > I love the design of ruby. Please don?t make me have > to use C or Java just because I want to do some > bitwise ops. It?s just a harmless codec I?m working on > :-) Actually I already did it in Java :-( b = 123 # which we know is 01111011 # if we want to test for bit 4, we bitwise-and with 0x08 and # test to make sure it doesn't equal 0: if b & 0x08 != 0 puts "bit 4 set" end # if we want to test that bit 3 is clear, we bitwise-and # with 0x04 and make sure it equals 0: if b & 0x04 == 0 puts "bit 3 clear" end # If we want to now set bit 3, we bitwise-or the value 0x04: b = b | 0x04 p b # => 127, or "01111111" which is 01111011 with bit 3 now set. -- Dossy -- Dossy Shiobara mail: dossy@panoptic.com Panoptic Computer Network web: http://www.panoptic.com/ "He realized the fastest way to change is to laugh at your own folly -- then you can let go and quickly move on." (p. 70)