对定义为无符号字节的位范围的数字执行有符号算术运算



我有两个字节。我需要把它们变成两个整数,其中前12位表示一个整数,后4位表示另一个整数。我想我可以&第二个带有0x0f的字节来获得4个比特,但我不知道如何将其转换为带有正确符号的字节。

更新:只是澄清一下,我有2个字节的

byte1 = 0xab
byte2 = 0xcd

我需要用它做一些类似的事情

var value = 0xabc * 10 ^ 0xd;

很抱歉造成混乱。

谢谢你的帮助。

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

尝试使用此代码

对于踢球:

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();

好吧,让我们再试一次,知道我们的拍摄目的。我在VS2008中尝试了以下操作,它似乎运行良好,即最后同时使用outOneoutTwo = -1。这就是你要找的吗?

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);

假设您有以下到字节:

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

并考虑0xab为前8位,0xcd为后8位,或0xabc为前12位,0xd为后4位。然后你可以得到这些比特如下;

int x = (a << 4) | (b >> 4);   // x == 0x0abc
int y = b & 0x0f;              // y == 0x000d

经过编辑以考虑对"签名"规则的澄清:

public void unpack( byte[] octets , out int hiNibbles , out int loNibble )
{
  if ( octets        == null ) throw new ArgumentNullException("octets");
  if ( octets.Length != 2    ) throw new ArgumentException("octets") ;
  int value = (int) BitConverter.ToInt16( octets , 0 ) ;
  // since the value is signed, right shifts sign-extend
  hiNibbles =   value >>  4         ;
  loNibble  = ( value << 28 ) >> 28 ;
  return ;
}

最新更新