1

I'd like to convert a hex string into an 8-bit signed integer, as shown in the following example:

irb> "0xff".unpack(X)
=> [-1]

The correct value for X is missing.

By reding https://ruby-doc.org/core-2.3.0/String.html#method-i-unpack and experimenting I do not find the correct value for X.


I could code that myself, like also posted here: https://www.ruby-forum.com/topic/138200#615299 but I am convinced, there is a more elegant concise ruby way.

irb> length = 8
irb> mid = 2**(length-1)
irb> max_unsigned = 2**length
irb> to_signed = proc {|n| (n>=mid) ? n - max_unsigned : n}
irb> to_signed["0xFF".to_i(16)]
=> -1

Note: For the unsinged case, this is easy:

irb> "e0".hex
=> 224

1 Answer 1

5

The c directive comes very close but it expects a different input: a single character representing the signed 8-bit integer. This requires the input "0xff" to be "\xff". So this conversion must take place first. At least one method known by you can be used here; the other one is Integer#chr:

"0xff".hex.chr # => "\xFF"

And the complete solution:

"0xff".hex.chr.unpack1(?c) # => -1
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.