2012-09-06 41 views
0

我必须写这个代码作家庭作业,但我甚至不知道从哪里开始。这是我必须编写的方法的javadoc。Java位操作:替换十六进制的半字节

/** 
* Sets a 4-bit nibble in an int 

* Ints are made of eight bytes, numbered like so: 7777 6666 5555 4444 3333 2222 1111 0000 
* 
* For a graphical representation of this: 
* 1 1 1 1 1 1     
* 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 
* |Nibble3|Nibble2|Nibble1|Nibble0| 
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 
* 
* Examples: 
*  setNibble(0xAAA5, 0x1, 0) //=> 0xAAA1 
*  setNibble(0x56B2, 0xF, 3) //=> 0xF6B2 
* 
* @param num int that will be modified 
* @param nibble nibble to insert into the integer 
* @param which determines which nibble gets modified - 0 for least significant nibble 
*    
* @return the modified int 
*/ 

这是我的。我已经将它与javadoc中的第一个示例一起使用,但我知道这并不适用于所有情况。特别是当int!= 0;

public static int setNibble(int num, int nibble, int which) 
    { 
    int newNibble = (num >> 4); 
    newNibble = (newNibble << 4) | nibble; 
    return newNibble; 
    } 

我应该使用班次吗?我被告知我可以在一行代码中执行此方法。 感谢您的高级帮助!

+1

你应该使用班次。 你在正确的轨道上。您当前的代码将保留原始值并添加新的半字节。您需要清除原始半字节。 –

回答

5

我建议你;

  • 提取您想保留通过构建掩模,通过&
  • 地方比特位要加进右位置左移<<
  • 按位结合他们或
+1

清洁和简单,一个很好的答案。我想补充的唯一一点是,虽然你可以在一行代码中做很多事情,但这取决于该代码行的可读性,根据你的舒适程度,它可能不值得可读性的代价。仍然这个问题很好地压缩到一条线。 –

+0

好吧,对于上面的例子(0xAAA5,0x1,0)// => 0xAAA1来掩盖它,我会使用AAA5&FFF0。我可以使用if语句来创建FFF0吗? –

+0

哦对不起。我的意思是与一个if和else * –

相关问题