From: Markus Date: 2004-09-23T04:27:10+09:00 Subject: Re: negative numbers and binary formats On Wed, 2004-09-22 at 11:14, Paul wrote: > Im trying to take a negative integer value, convert it to its binary > equivalent, and save its hex value So, are you wanting it in binary or in hex? Assuming (from your context) that you're wanting it in hexadecimal (base 16) instead of binary (base 2) you could write: (a & 0xff).to_s(16) for one byte values, (a & 0xffff).to_s(16) for two byte values, etc. If you are wanting it in binary you would instead write: (a & 0xff).to_s(2) > How do I do what Im trying to do - given my -7 in the example may be a > 1 byte, 2 byte or 4 byte value. If you don't know at code-time how large the value will be, but can determine it at run-time, you could write: (a & (((1 << (8*n)) - 1)).to_s(16) where n is the number of bytes in a and the expression involving a makes a mask if the proper size. Alternatively, you could mess with the result instead, by writing: ("0"*8 + (a & 0xffffffff).to_s(16))[-n*2..-1] which pads the result with zeros and then takes the least significant 2n hexits (i.e, the bottom n bytes). -- Markus