0
votes

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?

1
You might want to re-title your post, because "byte bashing" doesn't mean a lot to me. - Romain
Sure, Bytebashing (or more normally bit bashing) refers to modifying or interacting with values in the componany bytes (or more normally bits) - Lyndon White

1 Answers

1
votes

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:

1 byte: 11110001 
2 bytes: 1111111111110001
8 bytes: 1111111111111111111111111111111111111111111111111111111111110001

for positive values is the same:

1 byte: 00001111
2 bytes: 0000000000001111
8 bytes: 0000000000000000000000000000000000000000000000000000000000001111

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:

//If the MSB were raw[0]:
boolean isNegative = false;
if(raw[0] & 0x80 != 0){
      isNegative = true;
}