javabinaryuint8tuint16

How produce two's complement of a Uint16?


I have two bytes of data. I converted each of them to Uint8 then I produced a Uint16 from them.

How I can produce two's complement of this Uint16 number?

I've tried uInt16 = ~uInt16 + 1 but the code produces 32bit integer and I want it to stay a 16bit Integer.

    byte firstByte, secondByte;
    int firstUint8, secondUint8, uInt16;
    firstByte = buffer[index];//get first byte from buffer
    secondByte = buffer[index + 1];//get second byte from buffer


    firstUint8=firstByte & 0xFF;//produce Uint8
    secondUint8 = secondByte & 0xFF;//produce Uint8

    uInt16 = 256 * firstUint8 + secondUint8;//create Uint16 from these to    Uint8

    twosComplementOfUInt16=~number+1; //produce 32 bit integer but I want int16 

Solution

  • Java is not the best programing language to work with bits. But if you want you can read the documentation to see how the number are represented in java; how to work with bytes or you can do a tutorial.

    As observation the (~ and +) returns an integer

        public static void main(String[] args) {
            int uint8 = 0xff;
            int uint16 = 0xffff;
            long uint32 = 0xffffffff;
    
            int one = 0x0001;
            int ten = 0x000A;
            int twoComplementOfTen = 0xFFF6;
            int computedTwoComplementOfTen = ~ten + one;
            int revertTwoComplementOfTen = ~twoComplementOfTen + one;
    
            System.out.printf("One = 0x%04X \n", one);
            System.out.printf("ten = 0x%04X \n", ten);
            System.out.printf("~ten + one = 0x%04X \n", twoComplementOfTen);
            System.out.printf("Computed ~ten + one = 0x%04X \n", computedTwoComplementOfTen);
            System.out.printf("~twoComplementOfTen + one = 0x%04X \n", revertTwoComplementOfTen);
    
            System.out.printf("Computed ~ten + one with uint16 mask = 0x%04X \n", uint16 & computedTwoComplementOfTen);
            System.out.printf("~twoComplementOfTen + one with uint16 mask  = 0x%04X \n", uint16 & revertTwoComplementOfTen);
        }
    
    Output:
    
    One = 0x0001 
    Ten = 0x000A 
    ~ten + one = 0xFFF6 
    Computed ~ten + one = 0xFFFFFFF6 
    ~twoComplementOfTen + one = 0xFFFF000A 
    Computed ~ten + one with uint16 mask = 0xFFF6 
    ~twoComplementOfTen + one with uint16 mask  = 0x000A