从ruby中的STDIN一次读取四个字节

时间:2014-03-23 15:11:47

标签: ruby hex byte stdin

我想从STDIN一次连续读取四个字节,并以十六进制输出。 我尝试过使用read,readbyte,each_byte,但我似乎无法让它工作。

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

其中file是二进制文件。

1 个答案:

答案 0 :(得分:2)

使用Enumerable#each_slice

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

STDIN.each_char.each_slice(4) { |c4|
  # Do something with `c4`. `c4` is an array that contains up to 4 characters
}