【问题标题】:Setting a nibble of a 32-bit integer to a certain value [duplicate]将 32 位整数的半字节设置为某个值 [重复]
【发布时间】:2013-01-21 20:58:49
【问题描述】:

我被困在如何将 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;
}

【问题讨论】:

标签: java bit-manipulation nibble


【解决方案1】:
public static int setNibble(int num, int nibble, int which) {
    return num & ~(0xF << (which * 4)) | (nibble << (which * 4));
}

这里:

  • &amp; ~(0xF &lt;&lt; (which * 4)) 掩盖了半字节的原始值;
  • | (nibble &lt;&lt; (which * 4)) 将其设置为新值。

【讨论】:

  • @BevynQ:那行不通。我们要清除这些位,而不是翻转它们。
  • 太棒了!完全有道理!
【解决方案2】:
nibble &= 0xF; // Make sure
which &= 0x3;
int shifts = 4 * which; // 4 bits
num &= ~(0xF << shifts);
num |= nibble << shifts;
return num;

【讨论】:

    猜你喜欢
    • 2016-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-10
    • 1970-01-01
    • 1970-01-01
    • 2010-12-19
    • 1970-01-01
    相关资源
    最近更新 更多