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

Rob*_*met 1 c# binary

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

在此输入图像描述
这就是我现在拥有的:

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

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

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

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

Console.Write(LogicalLocation);
Run Code Online (Sandbox Code Playgroud)

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

Mat*_*son 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"));
Run Code Online (Sandbox Code Playgroud)

请注意,我也改变+=,以|=更好地表达发生了什么.