Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perform signed arithmetic on numbers defined as bit ranges of unsigned bytes

Tags:

c#

I have two bytes. I need to turn them into two integers where the first 12 bits make one int and the last 4 make the other. I figure i can && the 2nd byte with 0x0f to get the 4 bits, but I'm not sure how to make that into a byte with the correct sign.

update: just to clarify I have 2 bytes

byte1 = 0xab
byte2 = 0xcd

and I need to do something like this with it

var value = 0xabc * 10 ^ 0xd;

sorry for the confusion.

thanks for all of the help.

like image 529
scott Avatar asked Jul 01 '11 17:07

scott


4 Answers

int a = 10;
int a1 = a&0x000F;
int a2 = a&0xFFF0;

try to use this code

like image 97
Serghei Avatar answered Sep 30 '22 15:09

Serghei


For kicks:

public static partial class Levitate
{
    public static Tuple<int, int> UnPack(this int value)
    {
        uint sign = (uint)value & 0x80000000;
        int small = ((int)sign >> 28) | (value & 0x0F);
        int big = value & 0xFFF0;

        return new Tuple<int, int>(small, big);
    }
}

int a = 10;
a.UnPack();
like image 26
Ritch Melton Avatar answered Sep 30 '22 17:09

Ritch Melton


Ok, let's try this again knowing what we're shooting for. I tried the following out in VS2008 and it seems to work fine, that is, both outOne and outTwo = -1 at the end. Is that what you're looking for?

byte b1 = 0xff;
byte b2 = 0xff;
ushort total = (ushort)((b1 << 8) + b2);
short outOne = (short)((short)(total & 0xFFF0) >> 4);
sbyte outTwo = (sbyte)((sbyte)((total & 0xF) << 4) >> 4);
like image 42
Kongress Avatar answered Sep 30 '22 17:09

Kongress


Assuming you have the following to bytes:

byte a = 0xab;
byte b = 0xcd;

and consider 0xab the first 8 bits and 0xcd the second 8 bits, or 0xabc the first 12 bits and 0xd the last four bits. Then you can get the these bits as follows;

int x = (a << 4) | (b >> 4);   // x == 0x0abc
int y = b & 0x0f;              // y == 0x000d
like image 39
dtb Avatar answered Sep 30 '22 15:09

dtb