Re: Bitwise operations

From: Rob L.

I can’t understand how to access the first byte from
a string (a series of 8 bit bytes I believe). There don’t seem to be
any
bit-shift operators in Ruby for a string - could anybody
advise how I go about this ?

Strings in Ruby are, as you say, series of 8-bit bytes. The String#[]
operator when called with a single integer index returns the numeric
value of the requested byte:

irb(main):001:0> s = “\xf7\x23”
=> “\367#”
irb(main):002:0> s[0]
=> 247
irb(main):003:0> s[0].to_s(16)
=> “f7”

Gavin K. wrote:

Strings in Ruby are, as you say, series of 8-bit bytes. The String#[]
operator when called with a single integer index returns the numeric
value of the requested byte:

Reputedly about to change in Ruby 2, indexing a String will return a
single-character string. I think there’ll be some more clean separation
between methods operating on a String as a (possibly Unicode) text
string or as binary data. I’m still personally not quite happy with the
semantics of Strings being overloaded like this, but it’s probably the
most compatible way.

David V.

On 10/18/06, David V. [email protected] wrote:

Gavin K. wrote:

Strings in Ruby are, as you say, series of 8-bit bytes. The String#[]
operator when called with a single integer index returns the numeric
value of the requested byte:
Reputedly about to change in Ruby 2, indexing a String will return a
single-character string. I think there’ll be some more clean separation
between methods operating on a String as a (possibly Unicode) text
string or as binary data. I’m still personally not quite happy with the
semantics of Strings being overloaded like this, but it’s probably the
most compatible way.

Fortunately, it will be controlled where the encoding of the binary
blob that is the string is treated as a view on the data. Thus, when
the encoding is UTF-8, Ruby will try to interpret the characters
according to UTF-8 rules. When the encoding is none (or raw, or
something), Ruby won’t try to interpret the characters at all.

-austin

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs