Java位操作:替换十六进制的半字节 [英] Java Bit Operations: replacing nibble of hex

查看:132
本文介绍了Java位操作:替换十六进制的半字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须为家庭作业分配这段代码,但我什至不知道从哪里开始.这是我必须编写的方法的javadoc.

I have to write this code for a homework assignment but I don't even know where to start. Here is the javadoc to the method I have to write.

/**
* 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;

Here is what I have. I've got it to work with the first example in the javadoc, But I know this does not hold true for all cases. Especially when int which != 0;

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

我应该使用班次吗?有人告诉我可以在一行代码中执行此方法. 感谢您对高级的帮助!

Should I be using shifts or not? I was told I could do this method in one line of code. Thanks for the help in advanced!

推荐答案

我建议您;

  • 通过构造掩码并使用&
  • 提取要保留的位
  • 将要添加的位左移<<
  • 按位或将它们组合起来
  • extract the bits you want to keep by constructing a mask and using &
  • place the bits to want to add into the right position with left shift <<
  • combine them with bitwise OR

这篇关于Java位操作:替换十六进制的半字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆