[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Re: Bitwise operations

Gavin Kistner

10/18/2006 11:42:00 PM

From: Rob Lee
> 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"

2 Answers

David Vallner

10/18/2006 11:47:00 PM

0

Gavin Kistner 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 Vallner

Austin Ziegler

10/19/2006 12:59:00 AM

0

On 10/18/06, David Vallner <david@vallner.net> wrote:
> Gavin Kistner 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
--
Austin Ziegler * halostatue@gmail.com * http://www.halo...
* austin@halostatue.ca * http://www.halo...feed/
* austin@zieglers.ca