I have this code, it results '2'. I googled and searched books but found no good answer that helped me.
int i = 2;
int j = 3;
int x = i & j;
System.out.println (x);
Can anyone can explain.
Here, '&' is the bitwise and operator. Bits are set in the result only if they are set in both of the operands:
Here's the operation:
2: 00000010
& 3: 00000011
-----------
2: 00000010
Of course here, ints are 32 bits, and I only showed the last 8, but the first 24 are all zeroes for these numbers anyway.
It's a bitwise operator.
2 in binary is '10'. 3 in binary is '11'. The bitwise & operator compares them like so:
10
&11
--
10
For each column where both numbers are 1, it will return 1. In this case, the result is '10', which as an int is equal to 2.
Take these examples:
System.out.println(2 & 3);
System.out.println(3 & 4);
System.out.println(8 & 4);
System.out.println(9 & 5);
System.out.println(11 & 7);
// binary representation of above operations
System.out.println(0b10 & 0b11);
System.out.println(0b11 & 0b100);
System.out.println(0b1000 & 0b100);
System.out.println(0b1001 & 0b101);
System.out.println(0b1011 & 0b111);
They result in the output of:
2
0
0
1
3
2
0
0
1
3
Then go back and look at the binary representations and notice how the resulting answers are the Bitwise AND of the numbers (and not the Logical AND &&)
& is a bitwise operator that works as follows:
0 & 0 = 0
1 & 0 = 0
0 & 1 = 0
1 & 1 = 1
and hence 2 & 3 = 2:
2 ==> 00000000000000000000000000000010
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
3 ==> 00000000000000000000000000000011
---------
2 ==> 00000000000000000000000000000010
& is the bitwise AND
&& is the logical AND.
2 & 3 delivers correctly 2.
Expressed in binary representation:
10
11
--
10
Related
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
edit: This question is not a duplicate. The whole point is to solve the question using masks and bit shifts.
I have a terrible programming teacher that introduces concepts without explaining them or providing material to understand them, and he's to arrogant and confrontational too seek help from.
So naturally, I'm stuck on yet another question without any guidance.
Given an integer variable x, write Java code to extract and display each of the four bytes of that integer individually as 8-bit values.
I'm supposed to use masking and bit shift operations to answer this question. I understand that masking means turning bits "on or off" and I understand that an integer has 32 bits or 4 bytes. But that information doesn't help me answer the question. I'm not necessarily asking for the entire solution, but any help would be appreciated.
Using masks and shifting to extract bytes from an integer variable i,
The bytes from most significant (highest) to least are:
byte b3 = (byte)((i>>24));
byte b2 = (byte)((i>>16)&255);
byte b1 = (byte)((i>>8)&255);
byte b0 = (byte)((i)&255);
out.println("The bytes are " + b3 + ", " + b2 + ", " + b1 + ", " + b0);
You could use a ByteBuffer
int myInt = 123;
byte[] bytes = ByteBuffer.allocate(4).putInt(myInt).array();
Then you can do whatever you want with it. If you want all bits you could do something like this:
for(int i = 0; i < 4; i++)
{
for(int j = 0; j < 8; j++)
{
if(bytes[i] & (1 << j))
{
System.out.print("1");
}
else
{
System.out.print("0");
}
}
System.out.print(" ");
}
I have not tested this code because I do not have Java on this PC, but if it does not work let me know. However this sould give you a ruff idea of what has to be done.
Firstly you have to understand bitwise operators and operations. ( https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op3.html )
Boolean logic states that x & 1 = x and x & 0 = 0.
Knowing this we can create a mask for, lets say the least significant 4 bits of an 8 bit number: 11001101 & 00001111 = 1101 (205 & 0x0f = 13).
(we ignore the first 4 zeros and we got our 4 bits)
What if we need the most significant bits?
we apply the same idea, but now the mask will change, according to the bits we need: 11001101 & 11110000 = 11000000 (205 & 0xf0 = 192)
whoops... we got 4 zeros.
How can you get rid of that? Shifting to the right with 4 positions.
so 11000000 >> 4 = 1100 (most significant 4 bits)
I hope this example will help you to get a better understanding of bitwise operations.
One simple solution could be
bit0 = (x & 0xff000000) >> 24;
bit1 = (x & 0x00ff0000) >> 16;
bit2 = (x & 0x0000ff00) >> 8;
bit3 = (x & 0x000000ff);
(bit0 is MSB).
Masking isn't quite turning bits "on" or "off". It is a way to extract only the bits you want from the variable you are using. Lets say that you have the binary number 10011011 and you want the value of the rightmost 4 bits. To do this, you construct another binary number of the same length where there are 0's in the places that you don't want and 1's in the places that you do. Therefore, our binary number is 00001111. You then bitwise AND them together:
1 & 0 = 0
0 & 0 = 0
0 & 0 = 0
1 & 0 = 0
1 & 1 = 1
0 & 1 = 0
1 & 1 = 1
1 & 1 = 1
In java, using hex instead of binary since java doesn't have binary literals, this looks like
int result = 0x9B & 0x0F;
//result is 0xB (or 11 in decimal)
Bit shifting is just what it sounds like. If you have 10011111 and shift it right 2 bits you get 00100111. In java a bit shift of 2 looks like
int result = 0x9B >> 2;
For your program the idea is this:
Mask the rightmost byte of your integer
Shift integer right 8 bits
Repeat three more times
the following code will check to see if you have any duplicate characters in the string, but i don't understand the if clause:
public static boolean isUniqueChars(String str) {
int checker = 0;
for (int i = 0; i < str.length(); ++i) {
int val = str.charAt(i) - 'a';
if ((checker & (1 << val)) > 0)
return false;
checker |= (1 << val);
}
return true;
}
I tried to look up some references, I am new to bit shifting, all i understand is that << shifts the binary number left or right. Can you explain to me how checker |= (1 << val) works ? and that 'if' statement as well.
I was also going through this book Cracking the Code Interview and ended up googling for a clear explanations. Finally I understood the concept.
Here is the approach.
Note :
We will assume, in the below code, that the string is only lower case āaā through āzā. This will allow us to use just a single int.
Java integer is of size 32
Number of lower case alphabets is 26
So we can clearly set 0/1 (true or false) value inside one integer in
decimal notation.
It is similar to bool visited[32] .
bool uses 1 byte. Hence you need 32 bytes for storing bool visited[32].
Bit masking is a space optimization to this.
Lets start :
You are looping through all the characters in the string.
Suppose on i'th iteration you found character 'b' .
You calculate its 0 based index.
int val = str.charAt(i) - 'a';
For 'b' it is 1. ie 98-97 .
Now using left shift operator, we find the value of 2^1 => 2.
(1 << val) // 1<<1 => 10(binary)
Now let us see how bitwise & works
0 & 0 -> 0
0 & 1 -> 0
1 & 0 -> 0
1 & 1 -> 1
So by the below code :
(checker & (1 << val))
We check if the checker[val] == 0 .
Suppose we had already encountered 'b'.
check = 0000 0000 0000 0000 0000 1000 1000 0010 &
'b' = 0000 0000 0000 0000 0000 0000 0000 0010
----------------------------------------------
result= 0000 0000 0000 0000 0000 0000 0000 0010
ie decimal value = 2 which is >0
So you finally we understood this part.
if ((checker & (1 << val)) > 0)
return false;
Now if 'b' was not encountered, then we set the second bit of checker using bitwise OR.
( This part is called as bit masking. )
OR's Truth table
0 | 0 -> 0
0 | 1 -> 1
1 | 0 -> 1
1 | 1 -> 1
So
check = 0000 0000 0000 0000 0000 1000 1000 0000 |
'b' = 0000 0000 0000 0000 0000 0000 0000 0010
----------------------------------------------
result= 0000 0000 0000 0000 0000 1000 1000 0010
So that simplifies this part:
checker |= (1 << val); // checker = checker | (1 << val);
I hope this helped someone !
Seems like I am late to the party, but let me take a stab at the explanation.
First of all the AND i.e & operation:
0 & 0 = 0
1 & 0 = 0
0 & 1 = 0
1 & 1 = 1
So basically, if you are given a bit, and you want to find out if its 1 or 0, you just & it with a 1. If the result is 1 then you had a 1, else you had 0. We will use this property of the & below.
The OR i.e | operation
0 | 0 = 0
1 | 0 = 1
0 | 1 = 1
1 | 1 = 1
So basically, if you are given a bit, and you want to do something to it so that the output is always 1, then you do an | 1 with it.
Now, In Java the type int is 4 bytes i.e. 32 bits. Thus we can use an int itself as a data-structure to store 32 states or booleans in simpler terms, since a bit can either be 0 or 1 i.e false or true. Since we assume that our string is composed of only lower case characters, we have enough space inside our int to store a boolean for each of the 26 chars!
So first we initialize our data-structure that we call checker to 0 which is nothing but 32 zeros: 0000000000000000000000.
So far so good?
Now we go through our string, for each character, first we get an integer representation of the character.
int val = str.charAt(i) - 'a';
We subtract a from it because we want our integer to be 0 based. So if vals:
a = 0 i.e. `0000000000000000000000`
b = 1 i.e. `0000000000000000000001`
c = 2 i.e. `0000000000000000000010`
d = 4 i.e. `0000000000000000000100`
Now as seen above, a is 32 zeros, but rest of the characters have a single 1 and 31 zeros. So when we use these characters, we left shift each of them by 1, i.e. (1 << val), so each of them have a single 1 bit, and 31 zero bits:
a = 1 i.e. `0000000000000000000001`
b = 2 i.e. `0000000000000000000010`
c = 4 i.e. `0000000000000000000100`
d = 8 i.e. `0000000000000000001000`
We are done with the setup. Now we do 2 things:
First assume all characters are different. For every char we encounter, we want our datastructure i.e. checker to have 1 for that char. So we use our OR property descrived above to generate a 1 in our datastructure, and hence we do:
checker = checker | (1 << val);
Thus checker stores 1 for every character we encounter.
Now we come to the part where characters can repeate. So before we do step 1, we want to make sure that the checker already does not have a 1 at the position corresponding to the current character. So we check the value of
checker & (1 << val)
So with help of the AND property described above, if we get a 1 from this operation, then checker already had a 1 at that position, which means we must have encountered this character before. So we immediately return false.
That's it. If all our & checks return 0, we finally return true, meaning there were no character repititions.
1 << val is the same as 2 to the degree of val. So it's a number which has
just one one in its binary representation (the one is at position val+1, if you count from
the right side of the number to the left one).
a |= b means basically this: set in a all binary flags/ones from the
binary representation of b (and keep those in a which were already set).
The other answers explain the coding operator usages but i don't think they touch the logic behind this code.
Basically the code 1 << val is shifting 1 in a binary number to a unique place for each character for example
a-0001
b-0010
c-0100
d-1000
As you can notice for different characters the place of 1 is different
checker = checker | (1 << val)
checker here is Oring (basically storing 1 at the same place as it was in 1<<val)
So checker knows what characters have already ocurred
Let's say after the occurence of a,b,c,d checker would look like this
0000 1111
finally
if ((checker & (1 << val)) > 0)
checks if that character has already been occured before if yes return false.To explain you should know a little about AND(&) operation.
1&1->1
0&0->0
1&0->0
So checker currently have 1 in places whose corresponding characters have already occured the only way the expression inside if statement is true
if a character occurs twice which leads 1&1->1 > 0
This sets the 'val'th bit from the right to 1.
1 << val is a 1 shifted left val times. The rest of the value is 0.
The line is equivalent to checker = checker | (1 << val). Or-ing with a 0 bit does nothing, since x | 0 == x. But or-ing with 1 always results in 1. So this turns (only) that bit on.
The if statement is similar, in that it is checking to see if the bit is already on. The mask value 1 << val is all 0s except for a single 1. And-ing with 0 always produces 0, so most bits in the result are 0. x & 1 == x, so this will be non-zero only if that bit at val is not 0.
checker |= (1 << val) is the same as checker = checker | (1 << val).
<< is left bit shift as you said. 1 << val means it's a 1 shifted val digits left.
Example: 1 << 4 is 1000. A left bit shift is the same as multiply by 2. 4 left bit shifts are 4 times 1 multiplied by 2.
1 * 2 = 2 (1)
2 * 2 = 4 (2)
4 * 2 = 8 (3)
8 * 2 = 16 = (4)
| operator is bitwise or. It's like normal or for one bit. If we have more than one bit you do the or operation for every bit.
Example:
110 | 011 = 111
You can use that for setting flags (make a bit 1).
The if condition is similar to that, but has the & operator, which is bitwise and. It is mainly used to mask a binary number.
Example:
110 | 100 = 100
So your code just checks if the bit at place val is 1, then return false, otherwise set the bit at place val to 1.
It means do a binary OR on the values checker and (1 << val) (which is 1, left shifted val times) and save the newly created value in checker.
Left Shift (<<)
Shift all the binary digits left one space. Effectively raise the number to 2 to the power of val or multiply the number by 2 val times.
Bitwise OR (|)
In each binary character of both left and right values, if there is a 1 in the place of either of the two numbers then keep it.
Augmented Assignment (|=)
Do the operation (in this case bitwise OR) and assign the value to the left hand variable. This works with many operators such as:-
a += b, add a to b and save the new value in a.
a *= b, multiply a by b and save the new value in a.
Bitwise shift works as follows:
Example: a=15 (bit representation : 0000 1111)
For operation: a<<2
It will rotate bit representation by 2 positions in left direction.
So a<<2 is 0011 1100 = 0*2^7+0*2^6+1*2^5+1*2^4+1*2^3+1*2^2+0*2^1+0*2^0 = 1*2^5+1*2^4+1*2^3+1*2^2 = 32+18+8+4=60
hence a<<2 = 60
Now:
checker & (1<<val),
will always be greater then 0, if 1 is already present at 1<<val position.
Hence we can return false.
Else we will assign checker value of 1 at 1
I've been working on the algorithm and here's what I noticed that would also work. It makes the algorithm easier to understand when you exercise it by hand:
public static boolean isUniqueChars(String str) {
if (str.length() > 26) { // Only 26 characters
return false;
}
int checker = 0;
for (int i = 0; i < str.length(); i++) {
int val = str.charAt(i) - 'a';
int newValue = Math.pow(2, val) // int newValue = 1 << val
if ((checker & newValue) > 0) return false;
checker += newValue // checker |= newValue
}
return true;
When we get the value of val (0-25), we could either shift 1 to the right by the value of val, or we could use the power of 2s.
Also, for as long as the ((checker & newValue) > 0) is false, the new checker value is generated when we sum up the old checker value and the newValue.
public static boolean isUniqueChars(String str) {
int checker = 0;
for (int i = 0; i < str.length(); ++i) {
int val = str.charAt(i) - 'a';
if ((checker & (1 << val)) > 0)
return false;
checker |= (1 << val);
}
return true;
}
1 << val uses right shift operator. Let us say we have character z. ASCII code of z is 122. a-z is 97- 122 = 25. If we multiply 1*(2)^25 = 33554432. Binary of that is 10000000000000000000000000
if checker has 1 on its 26th bit then this statement if ((checker & (1 << val)) > 0) would be true and isUniqueChar would return false.
otherwise checker would turn it's 26th bit on. |= operator(bitwise or and assignment operator) does checker bitwise OR 10000000000000000000000000. Assigns the result to checker.
public class Operators {
public static void main(String[] args) {
int a = 12;
System.out.println("Bitwise AND:"+(12&12));
System.out.println("Bitwise inclusive OR:"+(12|12));
System.out.println("Bitwise exclusive OR:"+(12^12));
}
}
OUTPUT:
Bitwise AND:12
Bitwise inclusive OR:12
Bitwise exclusive OR:0
I understand first two, but not the third.
XOR tells whether each bit is different.
1 XOR 1 = 0
1 XOR 0 = 1
0 XOR 1 = 1
0 XOR 0 = 0
In other words "either but not both"
0011 XOR 0101 = 0110
BITWISE INCLUSIVE OR (|) means normal or operation ,
BITWISEE ExCLUSIVE OR (^) means xor operation
Third one is an XOR operation (Xclusive-OR)
It says, OR should be exclusively:
where similar will be False(0)
and dissimilar will be True(1).
So 12 in binary would be 1100
So, perform bitwise XOR here:
1 1 0 0
1 1 0 0
---------
0 0 0 0
---------
Every column has same digit, either both are 1's or both are 0's
XOR says, both should be different. Hence all zeros
Exclusive or (XOR) is defined as:
0 ^ 0 = 0
1 ^ 0 = 1
0 ^ 1 = 1
1 ^ 1 = 0
That is, it is 0 when two values are the same, 1 if they are different.
So, given two bit patterns which are exactly equal, each XORed bit will evaluate to 0, as each bit will either have 1 in both positions, or 0 in both positions.
Supposing the inputs are two integer values. I want to convert the two integer values to binary, perform binary addition, and give the result with the carry ignored (the integer equivalent). How would I go about doing this.
An idea that comes to mind is to convert them to binary strings in some way and use an algorithm for binary addition, and then ignore the carry (delete the carry character from the string, if the carry exists).
Sample Input
One number : 1
Second number : 3
Sample Output
2
Explanation:
The lowest bit in the sum is 1 + 1 = 0
The next bit is 0 + 1 = 1 (the carry from the previous bit is discarded)
The answer is 10 in binary, which is 2.
You are probably looking for the bitwise XOR (exclusive OR) which will provide the following outputs for the given inputs:
^ | 0 | 1
--+---+--
0 | 0 | 1
--+---+--
1 | 1 | 0
It behaves like binary addition ( 1+1 = 10) but ignores the overflow if both operands are 1.
int a = 5; // 101
int b = 6; // 110
a ^ b; // 3 or 011
This is just an XOR of the two integers in binary. In Java you can do
result = v1 ^ v2;