binary reading

R

ruby talk

a=File.open("c:\\1.txt")
a.binmode
print a.read(1)

it prints the char. how can i get and play with the bits and bytes of the file?
 
Z

Zach Dennis

ruby said:
a=File.open("c:\\1.txt")
a.binmode
print a.read(1)

it prints the char. how can i get and play with the bits and bytes of the file?

a=File.open("c:\\1.txt")
a.each_byte{ |byte|
#play with each character/byte here
}


Zach
 
B

Bill Atkins

Are you sure you want the binary? You can use the bitwise |, ~, and &
operators to manipulate the bits of the byte.
 
R

ruby talk

I looked at the unpack example
a=File.open("c:\\1.txt")
a.each_byte { |byte|
print byte.to_s.unpack('b8'),' ',byte,' '
}

But i get this for output
01101100 65 01101100 66
i know A!=B
and b* instead of b8 gives me
0110110010101100 65 0110110001101100 66

Becker
 
H

Hugh Sasse Staff Elec Eng

What about (written as if it were a patch):

- a=File.open("c:\\1.txt")
+ a=File.open("c:\\1.txt", 'rb')
a.each_byte { |byte|
- print byte.to_s.unpack('b8'),' ',byte,' '
+ print byte.chr.unpack('b8'),' ',byte,' '
}


Hugh
 
R

Robert Klemme

ruby talk said:
I looked at the unpack example
a=File.open("c:\\1.txt")
a.each_byte { |byte|
print byte.to_s.unpack('b8'),' ',byte,' '
}

But i get this for output
01101100 65 01101100 66
i know A!=B
and b* instead of b8 gives me
0110110010101100 65 0110110001101100 66
%08b\n", b.chr,b,b) } }
V 86 01010110
e 101 01100101
r 114 01110010
s 115 01110011
i 105 01101001
o 111 01101111
n 110 01101110
32 00100000
4 52 00110100
.. 46 00101110
4 52 00110100
32 00100000
B 66 01000010
u 117 01110101
i 105 01101001
l 108 01101100
d 100 01100100
32 00100000
1 49 00110001
6 54 00110110
2 50 00110010
=> #<File:buildnumber (closed)>

Regards

robert
 
R

ruby talk

10000010 65 01000010 66

the output is still wrong
I also tried adding a.binmode no luck.
Will i also have such a problem writing a binary file?
Becker
 
M

Mauricio Fernández

10000010 65 01000010 66

the output is still wrong

It's printing the LSB first. unpack("B8") would do what you expect.
Alternatively num.to_s(2) or "%08b" % num .
 

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

Members online

Forum statistics

Threads
474,161
Messages
2,570,892
Members
47,430
Latest member
7dog123

Latest Threads

Top