This question already has answers here:
Bitwise operator for simply flipping all bits in an integer?
(16 answers)
Closed 8 years ago.
I would like to flip all the bits in a byte. How would I do that?
Ex:
input: 10101000
output: 01010111
Use the ~ bitwise complement operator.
byte flipped = (byte) ~original;
Related
This question already has answers here:
How do you specify a byte literal in Java?
(6 answers)
How to specify a constant is a byte or short?
(3 answers)
Java binary literals - Value -128 for byte
(1 answer)
Closed 4 months ago.
So to convert a positive binary number into a negative one I have to invert all of the bits of the number and add 1.
`byte x = 0b0111_1111;
System.out.println(x); // 127
x = 0b1111_1111_1111_1111_1111_1111_1000_0001;
System.out.println(x); // -127
I don't understand why I have to expand my number to 32 bit form by adding zeros on the left side before reversing the bits, why exactly to 32 bit form?
This question already has answers here:
Convert integer into byte array (Java)
(11 answers)
Closed 8 years ago.
Suppose i have the number 520 that is mapped in two bytes that gives me the number: 1000001000 and i want to convert this number (520) to two other numbers, these numbers should be: 2 and 8 because 00000010 will give me 2 and 00001000 will give me 8. how can i do this with java?
Like this:
int theNumber = 520;
byte oneNumber = (byte)theNumber;
byte otherNumber = (byte)(theNumber >> 8);
This question already has answers here:
Print an integer in binary format in Java
(24 answers)
Closed 8 years ago.
Say I have an integer number: 11728322732
how can i convert it to a string according to its byte representation, i.e 11100011000000001100000111110001 (32 bits \ 4 bytes \ integer)
Thanks
Here it is:
Long.toBinaryString(11728322732L);
Actually, 11728322732 is not an Integer but a Long (because it is greater than Integer.MAX_VALUE). So if you really want to convert this long to a 32-bits int (can't figure why actually), you could do:
Integer.toBinaryString((int)11728322732L);
This question already has answers here:
Java code To convert byte to Hexadecimal
(23 answers)
Closed 9 years ago.
I have a MAC address represented as a byte[] in Java and want it as a hexadecimal string, as they are usually represented. How can I do this with as easy as possible?
The byte array has length 6.
Try this:
String hexValue = String.format("%02X:%02X:%02X:%02X:%02X:%02X", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
This question already has answers here:
What does the ^ operator do in Java?
(19 answers)
Closed 8 years ago.
What does the ^ (caret) mean in Java syntax? Why does 6^3 return 5?
It's the bitwise XOR operator. XOR is exclusive or.
6 in binary (lets assume 4 bits) is 0110, 3 in binary is 0011.
So, we get:
0110
0011 XOR
----
0101
And 0101 is 5.
See Bitwise and Bit Shift Operators.