首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将32位整数的半字节设置为某个值

将32位整数的半字节设置为某个值
EN

Stack Overflow用户
提问于 2013-01-22 04:58:50
回答 2查看 1.5K关注 0票数 3

我纠结于如何将4位值替换为原始32位整数的某个位置。非常感谢大家的帮助!

代码语言:javascript
复制
/**
 * 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;
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-01-22 05:05:46

代码语言:javascript
复制
public static int setNibble(int num, int nibble, int which) {
    return num & ~(0xF << (which * 4)) | (nibble << (which * 4));
}

这里:

  • & ~(0xF << (which * 4))屏蔽掉半字节的原始值;
  • | (nibble << (which * 4))将其设置为新值。
票数 2
EN

Stack Overflow用户

发布于 2013-01-22 05:06:03

代码语言:javascript
复制
nibble &= 0xF; // Make sure
which &= 0x3;
int shifts = 4 * which; // 4 bits
num &= ~(0xF << shifts);
num |= nibble << shifts;
return num;
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14447116

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档