I have a two’s complement representation of a number, in a byte array, and I want to expand it to use a larger byte array.
(You can get two’s complement byte[] out of BigIntegers)
So my new byte array must have the same sign bit (ie highest bit)
and then everything else shifted.
so:
byte[] resize (byte[] raw, int len)
{
byte high = raw[0];
resized[0] = high & 0x80 //ie binary 1000 0000
raw[0] = high & 0x7F // 0111 1111
//causes a side effect but i don't care raw is a throw away value
byte[] resized = new byte[len];
system.ArrayCopy(raw,0,resized,len-raw.length, len);
}
Am I on the right track?
I’m having trouble getting my head around, byte length hex literals work.
Or do my hex literals have to be int sized?
If so I’m going to have to cast my everything.
so is:
resized[0] = (byte) ((int)high & 0x8000)
raw[0] = (byte)((int)high & 0x7FFF)
The equivalent?
Step 1: save the sign bit (i.e: the Most Significant bit)
Step 2: the new padding bits should be the same as the sign bit. Example:
for positive values is the same:
Notice that when performing bitwise operations, the bytes are promoted to ints. Padding bytes will thus be 00h or FFh depending on the sign. The rest of the bytes are the same as the originals.
The sign can be determined as follows: