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