C-like cast from String to Integer needed

Hello,
I read some data from, for example, Tcp.
These data are read into a String.
Somewhere in these String are 4 bytes, which are the binary
representation of an Integer.
I hope there is a faster, native, solution than:
i = (((s[ofs+0]*256)+s[ofs+1])*256+s[ofs+2])*256+s[ofs+3]
… but I don’t see this.

In C++, it would look somehow like this:
char s[1024]; recv(so,s,sizeof s, 0); // this line not interesting
int y = (int)(s+ofs); // this line needed in Ruby.

Could pls somebody help me?

TIA,
Michael B.

Does this help?

str = “100101”
Integer(“0b” + str) # → 37

I’m sure there’s some other way to do it, and you might find it in the
pickaxe. (See www.ruby-doc.org if you don’t know what this is.)

Gavin

···

On Monday, February 17, 2003, 10:23:48 AM, Michael wrote:

Hello,
I read some data from, for example, Tcp.
These data are read into a String.
Somewhere in these String are 4 bytes, which are the binary
representation of an Integer.

Array#pack

···

On Mon, 17 Feb 2003 00:23:45 +0100, Michael Bruschkewitz wrote:

Hello,
I read some data from, for example, Tcp.
These data are read into a String.
Somewhere in these String are 4 bytes, which are the binary
representation of an Integer.
I hope there is a faster, native, solution than:
i = (((s[ofs+0]*256)+s[ofs+1])*256+s[ofs+2])*256+s[ofs+3]
… but I don’t see this.

Hi,

I read some data from, for example, Tcp.
These data are read into a String.
Somewhere in these String are 4 bytes, which are the binary
representation of an Integer.
I hope there is a faster, native, solution than:
i = (((s[ofs+0]*256)+s[ofs+1])*256+s[ofs+2])*256+s[ofs+3]
… but I don’t see this.

s.unpack(“@#{ofs}N”)

In C++, it would look somehow like this:
char s[1024]; recv(so,s,sizeof s, 0); // this line not interesting
int y = (int)(s+ofs); // this line needed in Ruby.

Note that it’s not portable.

···

At Mon, 17 Feb 2003 08:23:48 +0900, Michael Bruschkewitz wrote:


Nobu Nakada

Whoops. Looking at the other answers, I guess not.

Gavin

···

On Monday, February 17, 2003, 10:36:12 AM, Gavin wrote:

On Monday, February 17, 2003, 10:23:48 AM, Michael wrote:

Hello,
I read some data from, for example, Tcp.
These data are read into a String.
Somewhere in these String are 4 bytes, which are the binary
representation of an Integer.

Does this help?

str = “100101”
Integer(“0b” + str) # → 37

In article pan.2003.02.16.18.27.54.484044@nc.rr.com,
cyclists@nc.rr.com says…

Array#pack
which points me to → String#unpack
Now I see it too. Obviously, it is a little bit too late today.

Many Thanks.

-mb

For you, it was possibly to early at the morning where it was too late
at night for me :slight_smile:

Now I’m going to sleep.
-mb