Sergey Volkov
4/22/2006 11:18:00 AM
Sat, Apr 22 2006 6:12 am "ilhamik" <ilhami.kilic@gmail.com> wrote:
>I think it is not that i am looking for,
> the java version print as result [0,7,-95,32] for 500000
>
> how can i get the same result in ruby?
Use String object in Ruby for byte array in Java,
use String#<< to collect characters/bytes in Ruby String:
% cat tByteArr.rb
# 'Java array' implemented in Ruby (do not reproduce in your code!):
i=500000
bj=' '*4
bj[0] = (i&0xff000000)>>24
bj[1] = (i&0xff0000)>>16
bj[2] = (i&0xff00)>>8
bj[3] = i&0xff
# Ruby String
br=''
4.times{
br << (i&0xFF)
i >>= 8
}
br.reverse!
# check bj and br are the same
fail "different!" unless bj == br
# print out byte codes
br.each_byte{|c|
print c, " "
}
puts
__END__
% ruby tByteArr.rb
0 7 161 32
bytes are signed in Java, unsigned in Ruby,
so you can see 161 instead of -95,
internal bit representation in memory is the same;
Now you know how to reimplement your Java code in Ruby one-to-one,
but in your case. imho, better use pack/unpack Ruby feature.
good luck,
Sergey