Java – sets a 4-bit nibble in the int type

We need to propose a method to set 4-bit nibbles in int

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

This is what I wrote

But there are some mistakes I can't figure out

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

Update: I've put down the code But basically the answer is very clear. There are many good answers

Solution

You are very close;

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;
    }

In fact, you can simplify the code, but deal with = = 0 separately In fact, you are weighing for one shift instead of one There is not much difference. The code is clearer and more elegant

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

The idea of the mask is to completely clear the same four positions occupied by half bytes in the result Otherwise, the location will contain garbage in those bits where the nibble is zero 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!
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>