Question

I want to continously read four bytes at a time from STDIN and output that in hex. I have tried using both read, readbyte, each_byte, but I cant seem to get it working.

cat file | ./processor.rb
0x...
0x...
...

where file is a binary file.

Was it helpful?

Solution

Use Enumerable#each_slice:

STDIN.each_byte.each_slice(4) { |b4|
  # Do something with `b4`. `b4` is an array that contains up to 4 bytes
}

or

STDIN.each_char.each_slice(4) { |c4|
  # Do something with `c4`. `c4` is an array that contains up to 4 characters
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top