2

I have the following code to convert hex string to bytes in Java:

String s = "longhex";
int len = s.length();
byte[] data = new byte[(len / 2)];
for (int i = 0; i < len; i += 2)
{
    data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i + 1), 16));
}

is this a correct way to reproduce it in ruby?

s = "longhex"
bytes = []
(0..s.length / 2 - 1).step(2).each do |i|
   bytes[i / 2] = s[i].ord << 4 + s[i + 1].ord
end
Ilya Cherevkov
  • 1,673
  • 2
  • 17
  • 43

1 Answers1

1

No it is not correct. << has a lower operator precedence than +. Note even in java there are parentheses around shift operator. Also, it’s not ruby, it’s written with an almost ruby syntax.

 str.codepoints.
     each_slice(2).
     map { |f, l| (f << 4) + l }

would probably do what you want, but without seeing an expected outcome it’s hard to say.

Correct version as by Ilya is:

str.scan(/.{1}/).
    each_slice(2).
    map { |f, l| (Integer(f,16) << 4) + Integer(l,16) }
Aleksei Matiushkin
  • 105,980
  • 9
  • 87
  • 132