Ruby byte operations

I would like a hint on how I can get Ruby to work with byte arrays

Below is the C # code:

int t = (GetTime() / 60) //t is time in seconds divided by 60s (1 min)
byte[] myArray = new byte[64];
myArray[0] = (byte)(t >> 24);
myArray[1] = (byte)(t >> 16);

      

Any idea how I can get this to work in Ruby?

+3


source to share


2 answers


One way is to work with arrays of integers and use Array#pack

to package the result into a binary string. For example.

[65, 66, 67].pack('C*')

      



Returns ABC

Another way would be to manipulate the string directly when the encoding is set to "ASCII-8BIT"

+1


source


Ruby can do bitwise operations and you can use a regular array, so I don't see a problem. I am not using C # at the moment, so I cannot check if the results are the same.



t = Time.now.to_i / 60 #t is time in seconds divided by 60s (1 min)
myArray = []
myArray[0] = t >> 24
myArray[1] = t >> 16
p myArray #=>[1, 360]

      

0


source







All Articles