2013-06-24 62 views
1

我想取一个字节的前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 )+ 0×23(00100011),
所以结果我要实现的是0001 + 00100011 = 000100100011(为0x123)

+0

它几乎看起来像你认为'+'将执行字符串连接的等价物。是什么让你认为'0x51 + 0x23 = 000100100011'? – rliu

+0

我知道这是你读过的最聪明的评论,但是你的函数'ParseLocation'不会返回任何东西。 – fiscblog

回答

6

你需要离开

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

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

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

请注意,我也改变+=|=更好地表达的是什么H:位结合之前 - 换档通过8位UpperLogicalLocation appening。

3

问题是,您将高位存储在LogicalLocation的位0-3中而不是位8-11中。您需要将这些位移入正确的位置。以下更改应解决此问题:

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

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

LogicalLocation |= UnderLogicalLocation; 
3

你可以这样做:

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

...但要小心字节序!你的文档说UpperLogicalLocation应该存储在Byte 3,接下来的8位在Byte 4。做到这一点,需要将产生的int LogicalLocation正确拆分成这两个字节。