设置4位半字节在一个int类型 [英] set 4-bit nibble in an int type

查看:154
本文介绍了设置4位半字节在一个int类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们需要拿出在一个int设置的4位半字节的方法
输出应该是这样的:

we need to come up a method that set a 4-bit nibbles in an int output should like this:

 setNibble(0xAAA5, 0x1, 0); // => 0xAAA1
 setNibble(0x56B2, 0xF, 3); // => 0xF6B2

这是我写的......

This is what i wrote...

但也有一些错误,我无法弄清楚

but there have something wrong that I cannot figure out

setNibble(FFFF, 0, 0): Expected: FFF0 Result: FF00 
setNibble(FFFF, 6, 1): Expected: FF6F Result:  6FF 
setNibble(1312, E, 1): Expected: 13E2 Result:  E12 

更新:我已经放下了code只是柜面。但基本上,答案是非常清晰,而且上面有这么多伟大的答案。

update: I already put down the code just incase. but basically the answer is really clear and there are so many great answer above.

推荐答案

您是极为密切;

    public static int setNibble(int num, int nibble, int which)
    {
        int output;
        if(which ==0)
        {
            output = (num & /*65280*/ 0xFFFFFFF0 ) | nibble;
        }
        else
        {
            int shiftNibble = nibble << (4*which) ;
            int shiftMask = 0x0000000F << (4*which) ;
            output = (num & ~shiftMask) | shiftNibble ;
        }
        return output;
    }

在事实上,你可以在处理案件的代价简化code 这== 0 分开。事实上,你的交易关闭的如果的转变和不是。在所有没有太大的差别,以及code是更清晰,更优雅。

In fact, you can simplify the code at the expense of treating case which == 0 separately. In fact, you are trading-off an if for a shift and a not. Not much difference at all, and the code is much clearer and more elegant.

    public static int setNibble(int num, int nibble, int which) {
        int shiftNibble= nibble << (4*which) ;
        int shiftMask= 0x0000000F << (4*which) ;
        return ( num & ~shiftMask ) | shiftNibble ;
    }

面罩的想法是完全清楚的相同4个位置的半字节将在结果占据。否则,该位置将包含在半字节具有零位的那些垃圾。例如:

The idea of the mask is to completely clear the same 4 positions the nibble will occupy in the result. Otherwise, the position will contain garbage in those bits where the nibble has zeroes. For example

    // Nibble           77776666555544443333222211110000
    num=              0b01001010111101010100110101101010 ;
    nibble=           0b0010 ;  // 2
    which=            3 ;
    shiftNibble=      0b00000000000000000010000000000000 ;
    shiftMask=        0b00000000000000001111000000000000 ;
    num=              0b01001010111101010100110101101010 ;
    ~shiftMask=       0b11111111111111110000111111111111 ;  
    num & ~shiftMask= 0b01001010111101010000110101101010 ;
    //                                  ~~~~  Cleared!
    ( num & ~shiftMask ) 
      | nibble        0b01001010111101010010110101101010 ;
    //                                  ~~~~  Fully set; no garbage!

这篇关于设置4位半字节在一个int类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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