Java: calculate number complement using BitSet

Categories: Java; Tagged with: ; @ March 10th, 2015 20:15

Two’s complement is the way every computer I know of chooses to represent integers. To get the two’s complement negative notation of an integer, you write out the number in binary. You then invert the digits, and add one to the result.

www.cs.cornell.edu/~tomf/notes/cps104/twoscomp.html

    	Integer input = 50;
    	
    	String binString = Integer.toBinaryString(input);
    	BitSet bitSet = BitSet.valueOf(new long[] {input});
    	
    	for (int i = 0; i < binString.length(); i++) {
			bitSet.flip(i);
		}
    	
    	System.out.println(Arrays.toString(bitSet.toByteArray()));

<->



// Proudly powered by Apache, PHP, MySQL, WordPress, Bootstrap, etc,.