.unpack("B*")

B

Boris \BXS\ Schulz

Hi,

I have a problem with "unpack".
When I try to unpack a string, I can easily adress the individual chars
via the array.
But when I try to extract the binary values of a string, this does not
work anymore. I can neither adress individual binary digits, nor the 8
bits corresponding to a char.
Is this a feature or a bug ? And what can I do to adress the bits
individually ? Further, how do I get the binary values of an integer ?

char = "ABCDE"
myint = char.unpack("B*")
puts myint >> 0100000101000010010000110100010001000101
puts myint[3] >> nil

greetings, BXS
 
M

Mike Stok

Hi,

I have a problem with "unpack".
When I try to unpack a string, I can easily adress the individual chars
via the array.
But when I try to extract the binary values of a string, this does not
work anymore. I can neither adress individual binary digits, nor the 8
bits corresponding to a char.
Is this a feature or a bug ? And what can I do to adress the bits
individually ? Further, how do I get the binary values of an integer ?

char = "ABCDE"
myint = char.unpack("B*")
puts myint >> 0100000101000010010000110100010001000101
puts myint[3] >> nil

unpack returns an Array:

irb --simple-prompt
char = "ABCDE" => "ABCDE"
myint = char.unpack("B*") => ["0100000101000010010000110100010001000101"]
puts myint[0][3 .. 3]
0
=> nil
48
=> nil=> "0100000101000010010000110100010001000101"

Hope this helps,

Mike
 
M

Mike Stok

Boris \"BXS\" Schulz said:
And what can I do to adress the bits
individually ? Further, how do I get the binary values of an integer ?

I don't quite understand what this means, but

'ABCDE'.each_byte do |b|
0.upto(7) do |bit|
print "(#{b[bit]})"
end
print "\n"
end

prints

(1)(0)(0)(0)(0)(0)(1)(0)
(0)(1)(0)(0)(0)(0)(1)(0)
(1)(1)(0)(0)(0)(0)(1)(0)
(0)(0)(1)(0)(0)(0)(1)(0)
(1)(0)(1)(0)(0)(0)(1)(0)

where Fixnum#[] is used to access the bits of each byte

-------------------------------------------------------------- Fixnum#[]
fix[ n ] -> 0, 1
------------------------------------------------------------------------
Bit Reference---Returns the nth bit in the binary representation of
fix, where fix[0] is the least significant bit.
a = 0b11001100101010
30.downto(0) do |n| print a[n] end
produces:
0000000000000000011001100101010

Hope this helps,

Mike
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Staff online

Members online

Forum statistics

Threads
474,141
Messages
2,570,817
Members
47,361
Latest member
eitamoro

Latest Threads

Top