This question already has answers here:
Creating a "logical exclusive or" operator in Java
(19 answers)
Closed 5 years ago.
Given a number, i want to toggle the bits of number 'n'
say for example if n = 6 -> 0110
i want to get, result = 9 -> 1001
toggle , i.e
convert 1 to 0 & convert 0 to 1 in the binary representation
how to do this programmatically in java, by doing XOR of num with 1's
Thanks all for answers, so it depends of how many bits i want to toggle
say for ex, if its 8 bits then 0xff
if its entire 32 bits then oxffffffff
1 way would be n ^ ~0
You could do exactly that.
int y = 6^0xf
If you want to use the full int, then you have to XOR with -1 (twos complement means this is all 1's).
int y = 6^-1;
You can also use a different representation to make writing it out more intuitive.
int mask = 0xffffffff; //also -1
public static void main(final String[] args) {
final int n = 0b0110;
System.out.println(Integer.toBinaryString(n));
final int m = n ^ 0xffffffff;
System.out.println(Integer.toBinaryString(m));
}
Related
This question already has an answer here:
How does long to int cast work in Java?
(1 answer)
Closed 2 years ago.
public static void main(String[] args) {
long x = 164997969936395L;
int a = (int)(x >>> 16);
System.out.println(a); //Prints -1777298077
long b = (x >>> 16);
System.out.println(b); //Prints 2517669219
}
Trying to bitshift x by 16 bits, but the output differs depending on whether i use a long or an int, also it seems when i use long the negative signs are always gone.
I've also noticed when using int it really is divided by 2^16 whereas using long it is not, what's happening there?
In the first case, 2517669219, which is x >>> 16, is narrowed down to an int.
int can represent values in the range [-2147483648, 2147483647].
2517669219 is greater than 2147483647, so overflow happens.
I'm trying to convert a negative long number (e.g. -1065576264718330231L) to binary.
First, I convert negative number to positive one by removing the sign;
Second, I get the binary of the result from first step;
then I get stuck with "add one" to the binary result of the second step,that is :
please! how to implement the third step?
or do you have other better solutions?!
http://geekexplains.blogspot.com/2009/05/binary-rep-of-negative-numbers-in-java.html
Signed integers/longs use the two-complements notation:
Say you have -6:
6 = 000..000 110 binary
111..111 001 one's complement
111..111 010 add 1
-6 = 111..111 010
The advantage is that normal binary addition works (-6+6=0), there is just one 0.
Of you could simply subtract 6 from 0:
000
110
------ -
0
1 borrow 1 (all ones at the top)
0
...111
111...111010 = -6
Note:
If one borrows (subtracts one of) 0000000, one actually uses an overflow:
(1)0000000 which minus 1 delivers
1111111
Goodies:
long n = -1065576264718330231L;
System.out.println(Long.toUnsignedString(n, 2));
System.out.println(Long.toString(n, 2));
Given the long value is -1065576264718330231L.
long v = -1065576264718330231L;
System.out.println(Long.toBinaryString(v));
Or you can code the algorithm yourself
StringBuilder sb = new StringBuilder();
while (v != 0) {
sb.append(v < 0 ? '1'
: '0');
v <<= 1;
}
System.out.println(sb.toString());
If you want to convert a positive number to negative using 2's complement you can do the following:
long pos = 23;
long neg = ~pos + 1;
System.out.println(pos);
System.out.println(neg);
But all Strings, ints, longs, etc. are inherently stored in binary and are displayed in different formats based on context.
The output is 9 and I can't get my head around the whole bitwise XOR concept.
public class XOR {
public static void main( String[] args ) {
int a = 12;
int b = 5;
int c = a ^ b;
System.out.print( c );
}
}
XOR stands for exclusive or
Exclusive or or exclusive disjunction is a logical operation that outputs true only when inputs differ (one is true, the other is false)
in your case, it's a bitwise comparison, so each 0 and 1 at the same position is compared
first step is to translate values from decimal to binary
12 = 00001100
05 = 00000101
Then, you apply XOR
12 = 00001100
05 = 00000101
XOR = 00001001
Finally, you convert from binary to decimal
00001001 = 9
the XOR operator first converts both of your values into their binary equivalents. Binary operations will apply to corresponding bits, and the XOR operator evaluates to true (1) whenever the corresponding bits are not equal. For example, 2^1 = 3 [10 ^ 01] notice the first bits and the second bits are different, so both bits evaluate to 1.
In your example: 12 ^ 5
12 = 1 1 0 0
5 = 0 1 0 1
The first and the 4th bits are of opposite value, so the first and the fourth bits evaluate to 1, while the remaining bits evaluate to 0, so the solution is 1001 = 9
This question already has answers here:
long value with 0 on left
(5 answers)
Closed 5 years ago.
class LetsComp {
public static void main(String[] args) {
int a = 10, b = 0010;
System.out.println(a == b); // this gives false, even if both values in actual are same
}
}
In java 10 and 0010 are not the same.
0010 is in octal equivalent to 8 (in decimal), while 10 is already in decimal format.
From JLS:
An octal numeral consists of an ASCII digit 0 followed by one or more of the ASCII digits 0 through 7 interspersed with underscores, and can represent a positive, zero, or negative integer.
Here is my FIRST Question
Here is my code:
public class Bits{
public static void main(String args[]){
int i = 2 , j = 4;
int allOnes = ~0;
int left = allOnes << (j+1);
System.out.println("Binary Equivalent at this stage: " +Integer.toBinaryString(left));
}
}
The following is the output I'm getting:
Binary Equivalent at this stage: 11111111111111111111111111100000
How can I restrict it to only 8 bits from the right hand side. I mean 11100000 .
Please explain.
Here is my SECOND Question:
Also, I have one more Question which is totally different with the above one:
public static void main(String args[]){
int i = 2 , j = 4;
int allOnes = ~0; // will equal sequence of all 1s
int left = allOnes << (j+1);
System.out.println("Binary Equivalent at this stage: " +Integer.toBinaryString(left));
}
}
Since I didn't understand the following line:
int allOnes = ~0; // will equal sequence of all 1s
When I tried to output the value of "allOnes" then I got "-1" as my output.
I'm having hard time understanding the very next line which is as follows:
int left = allOnes << (j+1);
int allOnes = ~0;
Takes the integer 0 and applies the NOT operation bitwise so it will have all ones in its binary representation. Intagers use the two's complement format, meaning that a value of a word having all bits as one is value of -1.
If you only care about byte boundaries, then use a ByteBuffer
byte lastByte = ByteBuffer.allocate(4).putInt(i).array()[3];
To restrict this byte to the first four or last four bits, use lastByte & 0b11110000 or lastByte & 0b00001111
The integer representation of -1 is all 1's, i.e. 32 bits all set to 1. You can think of the first bit as -2^31 (note the negative sign), and of each subsequent bit as 2^30, 2^29, etc. Adding 2^0 + 2^1 + 2^2 ... + 2^30 - 2^31 = -1.
I suggest reading this tutorial on bitwise operations.
For #1 Integer.toBinaryString(left) is printing 32 bits (length of Integer), so if you just want the right 8 you can do the following:
Integer.toBinaryString(left).substring(24)
The ~ operator in Java inverts the the bit pattern. Thus 0 turns into ffff.
The << operator shifts the bits by x. You are shifting the bits to the left by 5 so you end up with 5 zeros on the right.
Here are all the bitwise operators for Java
First, a more general solution for the first question than what I've seen so far is
left &= (2 ^ n) - 1;
where n is the number of binary digits that you want to take from the right. This is based around the bitwise AND operator, &, which compares corresponding bits in two numbers and outputs a 1 if they are both 1s and 0 otherwise. For example:
10011001 & 11110000 == 10010000; // true
This is used to create what are known as bitmasks (http://en.wikipedia.org/wiki/Mask_(computing)). Notice how in this example how the left 4 bits of the first number are copied over to the result and how those same 4 bits are all ones in the second number? That's the idea in a bit mask.
So in your case, let's look at n = 8
left &= (2 ^ 8) - 1;
left &= 256 - 1;
left &= 255; // Note that &=, like += or *=, just means left = left & 255
// Also, 255 is 11111111 in binary so it can be used as the bitmask for
// the 8 rightmost bits.
Integer.toBinaryString(left) = "11100000";
Your second question is much more in depth, but you'd probably benefit most from reading the Wikipedia article (http://en.wikipedia.org/wiki/Two's_complement) instead of trying to understand a brief explanation here.
8 bits in decimal has a maximum value of 255. You can use the modulo (remainder) division operator to limit it to 8 bits at this point. For isntance:
int yournum = 35928304284 % 256;
will limit yournum to 8 bits of length. Additionally, as suggested in the comments, you can do this:
int yournum = 3598249230 & 255;
This works as well, and is actually preferred in this case, because it is much faster. The bitwise and function returns 1 if both associated bits are 1; since only the last 8 bits of 255 are one, the integer is implicitly limited to 255.
To answer your second question: A tilde is the bitwise inversion operator. Thus,
int allOnes = ~0;
creates an integer of all 1s. Because of the way twos complements works, that number actually represents -1.