将部分字节附加到另一个字节

时间:2013-06-24 08:13:32

标签: c# binary

我想取一个字节的前4位和另一位的所有位并将它们相互附加。
这是我需要实现的结果:

enter image description here
这就是我现在所拥有的:

private void ParseLocation(int UpperLogicalLocation, int UnderLogicalLocation)
{
    int LogicalLocation = UpperLogicalLocation & 0x0F;   // Take bit 0-3
    LogicalLocation += UnderLogicalLocation;
}

但这并没有给出正确的结果。

int UpperLogicalLocation_Offset = 0x51;
int UnderLogicalLocation = 0x23;

int LogicalLocation = UpperLogicalLocation & 0x0F;   // Take bit 0-3
LogicalLocation += UnderLogicalLocation;

Console.Write(LogicalLocation);

这应该给出0x51(0101 0001 )+ 0x23(00100011),
所以我想要实现的结果是0001 + 00100011 = 000100100011(0x123)

3 个答案:

答案 0 :(得分:6)

在组合位之前,您需要将UpperLogicalLocation位左移8:

int UpperLogicalLocation = 0x51;
int UnderLogicalLocation = 0x23;

int LogicalLocation = (UpperLogicalLocation & 0x0F) << 8;   // Take bit 0-3 and shift
LogicalLocation |= UnderLogicalLocation;

Console.WriteLine(LogicalLocation.ToString("x"));

请注意,我还将+=更改为|=,以便更好地表达正在发生的事情。

答案 1 :(得分:3)

问题是你将高位存储到LogicalLocation的0-3位而不是8-11位。您需要将位移到正确的位置。以下更改应解决问题:

int LogicalLocation = (UpperLogicalLocation & 0x0F) << 8;

另请注意,使用逻辑运算符或运算符更加惯用地组合这些位。所以你的第二行变成了:

LogicalLocation |= UnderLogicalLocation;

答案 2 :(得分:3)

你可以这样做:

int LogicalLocation = (UpperLogicalLocation & 0x0F) << 8;   // Take bit 0-3
LogicalLocation |= (UnderLogicalLocation & 0xFF);

...但要注意字节序!您的文档说UpperLogicalLocation应存储在Byte 3中,Byte 4中的后8位。要做到这一点,生成的int LogicalLocation需要正确地分成这两个字节。

相关问题