Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/342.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 将32位整数的半字节设置为特定值_Java_Bit Manipulation_Nibble - Fatal编程技术网

Java 将32位整数的半字节设置为特定值

Java 将32位整数的半字节设置为特定值,java,bit-manipulation,nibble,Java,Bit Manipulation,Nibble,我一直在研究如何将4位值替换为原始32位整数的某个位置。非常感谢您的帮助 /** * Set 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

我一直在研究如何将4位值替换为原始32位整数的某个位置。非常感谢您的帮助

/**
 * Set 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 The int that will be modified.
 * @param nibble The nibble to insert into the integer.
 * @param which Selects which nibble to modify - 0 for least-significant nibble.
 *            
 * @return The modified int.
 */
public static int setNibble(int num, int nibble, int which)
{
           int shifted = (nibble << (which<<2));
       int temp = (num & shifted);
           //this is the part I am stuck on, how can  I replace the original
           // which location with the nibble that I want? Thank you!
       return temp;
}
/**
*在int中设置4位半字节。
* 
*整数由八个字节组成,编号如下:
*   7777 6666 5555 4444 3333 2222 1111 0000
*
*对于此的图形表示:
*   1 1 1 1 1 1                 
*   5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 
*  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*|咬3 |咬2 |咬1 |咬0|
*  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* 
*示例:
*setNibble(0xAAA5,0x1,0);//=>0xAAA1
*setNibble(0x56B2,0xF,3);//=>0xF6B2
* 
*@param num将被修改的int。
*@param nibble要插入整数的半字节。
*@param,用于选择要修改的半字节-0为最低有效半字节。
*            
*@返回修改后的整数。
*/
公共静态int-setNibble(int-num,int-nibble,int-which)
{
int-shift=(半字节
公共静态int-setNibble(int-num,int-nibble,int-which){
返回num&~(0xF
nibble&=0xF;//确保
其中&=0x3;
int shift=4*其中;//4位

num&=~(0xF)32位
int
包含四个字节(8个半字节),而不是代码中的注释所述的八个字节。与您在@BevynQ之前提出的问题相同:这行不通。我们希望清除位,而不是翻转位。太棒了!完全有意义了!
public static int setNibble(int num, int nibble, int which) {
    return num & ~(0xF << (which * 4)) | (nibble << (which * 4));
}
nibble &= 0xF; // Make sure
which &= 0x3;
int shifts = 4 * which; // 4 bits
num &= ~(0xF << shifts);
num |= nibble << shifts;
return num;