Consider:
int a = 0;
a |= 1 << a;
System.out.println(a);
It prints "1". Why? I thought left bit shifting 0 by any number of times was still 0. Where's it pulling the 1 from?
The expression 1 << a; will shift the value 1, a number of times.
In other words, you have the value 1:
0000001
Now, you shift the whole thing over 0 bits to the left. You then have:
0000001
You then have:
a |= 1 << a;
Which resolves to:
a = 0000000 | 0000001
Or:
a = 1;
You might have the operands mixed up. If you're trying to shift the value 0 one bit to the left, you'd want:
a |= a << 1;
You are using the operator << in a wrong way.
It must to be:
int a = 0;
a |= a << 1;
System.out.println(a);
You are left shifting the literal 1 by the variable a. The value of variable a is zero. 1<<0 = 1
So you've just got your variables flipped. Try reversing the variables.
Related
Here is the description:
In order to stop the Mad Coder evil genius you need to decipher the encrypted message he sent to his minions. The message contains several numbers that, when typed into a supercomputer, will launch a missile into the sky blocking out the sun, and making all the people on Earth grumpy and sad.
You figured out that some numbers have a modified single digit in their binary representation. More specifically, in the given number n the kth bit from the right was initially set to 0, but its current value might be different. It's now up to you to write a function that will change the kth bit of n back to 0.
Example
For n = 37 and k = 3, the output should be
killKthBit(n, k) = 33.
3710 = 1001012 ~> 1000012 = 3310.
For n = 37 and k = 4, the output should be
killKthBit(n, k) = 37.
The 4th bit is 0 already (looks like the Mad Coder forgot to encrypt this number), so the answer is still 37."
Here is a solution I found and I cannot understand it:
int killKthBit(int n, int k)
{
return n & ~(1 << (k - 1)) ;
}
Can someone explain what the solution does and its syntax?
Detailed explanation of your function
The expression 1 << (k - 1) shifts the number 1 exactly k-1 times to the left so as an example for an 8 Bit number and k = 4:
Before shift: 00000001
After Shift: 00010000
This marks the bit to kill. You see, 1 was shifted to the fourth position, as it was on position zero. The operator ~ negates each bit, meaning 1 becomes 0 and 0 becomes 1. For our example:
Before negation: 00010000
After negation: 11101111
At last, & executes a bit-wise AND on two operands. Let us say, we have a number n = 17, which is 00010001 in binary. Our example now is:
00010001 & 11101111 = 00000001
This is, because each bit of both numbers is compared by AND on the same position. Only positions, where both numbers have a 1 remain 1, all others are set to 0. Consequently, only position zero remains 1.
Overall your method int killKthBit(int n, int k) does exactly that with binary operators, it sets the bit on position k of number n to 0.
Here is my try
//Returns a number that has all bits same as n
// except the k'th bit which is made 0
int turnOffK(int n, int k)
{
// k must be greater than 0
if (k <= 0) return n;
// Do & of n with a number with all set bits except
// the k'th bit
return (n & ~(1 << (k - 1)));
}
public class Operator {
public static void main(String[] args) {
byte a = 5;
int b = 10;
int c = a >> 2 + b >> 2;
System.out.print(c); //prints 0
}
}
when 5 right shifted with 2 bits is 1 and 10 right shifted with 2 bits is 2 then adding the values will be 3 right? How come it prints 0 I am not able to understand even with debugging.
This table provided in JavaDocs will help you understand Operator Precedence in Java
additive + - /\ High Precedence
||
shift << >> >>> || Lower Precedence
So your expression will be
a >> 2 + b >> 2;
a >> 12 >> 2; // hence 0
It's all about operator precedence. Addition operator has more precedence over shift operators.
Your expression is same as:
int c = a >> (2 + b) >> 2;
Is this what you want?
int c = ((a >> 2) + b) >> 2;
You were shifting to the right by whatever is 2+b. I assume you wanted to shift 5 by 2 positions, right?
b000101 >> 2 == b0001ΓΈΓΈ
| |___________________|_|
| |
|_____________________|
i.e. the leftmost bit shifts to the right by 2 positions and right most bit does as well (but is has no more valid positions left on its right side so it simply disappears) and the number becomes what's left - in this case '1'. If you shift number 5 by 12 positions you will get zero as 5 has less than 12 positions in binary form. In case of '5' you can shift by 2 positions at most if you want to preserve non-zero value.
I'm working on a program for class and was asked to figure out what <<= means and I found that << means a left shift of bits. I'm not sure what a left shift of bits is either though
This is equivalent to += or -= or similar operators. The operator << makes a copy of the variable and shifts it left. You must then assign this to a variable or use it in some way. The code:
x << 2;
does nothing. You must use this value in some way:
x = x << 2;
x <<= 2;
These are equivalent statements.
A left shift operator simply moves every bit of a variable to the left. Say we have defined the following variables:
char c = 5;
char d = 5;
lets say char is a 8-bit variable. In this case, c and d's binary form would look like this:
00000101
When a left shift is performed on c, every bit would move to the left:
c <<= 1; // now c = 00001010
d <<= 2; // now d = 00010100
Question is based on this site.
Could someone explain the meaning of these lines:
private int getBitValue(int n, int location) {
int v = n & (int) Math.round(Math.pow(2, location));
return v==0?0:1;
}
and
private int setBitValue(int n, int location, int bit) {
int toggle = (int) Math.pow(2, location), bv = getBitValue(n, location);
if(bv == bit)
return n;
if(bv == 0 && bit == 1)
n |= toggle;
else if(bv == 1 && bit == 0)
n ^= toggle;
return n;
}
int v = n & (int) Math.round(Math.pow(2, location));
Math.pow(2, location) raises 2 to the given power. This is rounded and converted to an integer. In binary, this will be 00000001 if location==0, 00000010 if location==1, 00000100 if location==2, etc. (Much better would be 1 << location which shifts a "1" by a certain number of bits, filling in 0 bits at the right. Using Math.pow will probably try to compute the logarithm of 2 every time it's called.)
n & ... is a bitwise AND. Since the item on the right has just one bit set, the effect is to zero out every bit in n except for that one bit, and put the result in v. This means that v will be 0 if that one bit is 0 in n, and something other than 0 if that bit is `, which means
return v==0?0:1;
returns 0 if the bit is clear and 1 if it's set.
int toggle = (int) Math.pow(2, location), bv = getBitValue(n, location);
toggle is set to that Math.pow thing I already described. bv is set to the bit that's already in n, which is 0 or 1. If this equals the thing you're setting it to, then we don't need to do anything to n:
if(bv == bit)
return n;
Otherwise, either we need to set it to 1 (remember that toggle will have just one bit set). n |= toggle is the same as n = n | toggle. | is a bit-wise OR, so that one bit will be set in n and all other bits in n will remain the same"
if(bv == 0 && bit == 1)
n |= toggle;
Or we need to set the bit to 0. n ^= toggle is the same as n = n ^ toggle. n is an exclusive OR. If we get here, then the bit in n is 1, and the bit in toggle is 1, and we want to set the bit in n to 0, so exclusive OR will change that bit to 0 while leaving every other bit the same:
else if(bv == 1 && bit == 0)
n ^= toggle;
The getBitValue just gets the value of a specified bit (on a certain location)
The setBitValue sets the value of a bit on the matched specific location.
These getter/setter methods are usually used for image processing, i.e. if you have a musk and you want to change a specific bit value.
Nothing more or less.
I have a long number like:
long l = Long.parseLong("10*000001111110" , 2) ;
Now, I want to add two bits in one position (say 2nd position, marked as *) into the long number.
Like,
long l = Long.parseLong("10*11*000001111110" , 2) ; (given between *)
Can anybody help me how to do that ? Note that I give an example to illustrate what I want. In real, I have only long land I have to work on it.
Edit:
1) position is not constant may be 0, 1 , 2 .. whatever.
2) and msb's can be 0. Means,
long l = Long.parseLong("00000010*000001111110" , 2) ;
long l = Long.parseLong("00000010*11*000001111110" , 2) ;
It sounds like you want something like bitStuffing where masking (&, ~, ^, and |) and shifting (>> and <<) are your instruments of choice.
long insertBit(long p_orignal, long p_new_bits, int p_starting_position_from_right, int p_ending_position_from_right)
{
long returnValue = p_original;
long onlyNewBits = 0;
// Set the bit to zero
long mask = (0xFFFFFFFFFFFFFFFFl);
for (int i=p_starting_position_from_right; i<=p_ending_position_from_right; i++)
{
mask ^ (1l << i);
}
returnValue = returnValue & mask;
mask = ~mask;
onlyNewBits = ~(p_new_bits & mask);
returnValue |= onlyNewBits;
return returnValue;
}
Disclaimer: I don't have a Java compiler available to compile this, but it should be something like this.
The first idea I had is the following:
Extract the first x bits that needs to stay on the position they are (in your example: 10) -> you could do this by running through a loop which creates the appropriate bitmask:
long bitmask = 1;
for(long bit = 1; bit < index; bit++) {
bitmask = (bitmask << 1) | 1;
}
Now you can create the long number that gets inserted -> just shift that number index positions to the left.
After that, you can easily build the new number:
long number = (((oldNumber >> index) << index) << insertionLength) | (insertion << index) | (oldNumber && bitmask);
Note: ((oldNumber >> index) << index) clears out the right part of the number (this part gets appended at the end using the bistmask). then you just need to shift this result by the length of the insertion (make space for it) and or it with the insertion (this needs to get shifted to the left by the index where to insert: (insertion << index). Finally, or the last part of the number (extracted via the bitmask: oldNumber && bitmask) to this result and you are done.
Note: I haven't tested this code. However, generally it should work but you may need to check my shifts (either it is index or index - 1 or so)!
If you only have the Long value say 123 you need to first convert this to a binary string. Like so:
String binaryValue = Long.toBinaryString("123L");
Then we take the string representation and perform a manipulation a specific character like so:
char[] characters = binaryValue.toCharArray();
char desiredCharacter = characters[index];
if(desiredCharacter == '1')
{
if(newValue == '1')
{
desiredCharacter = '0';
}
}else{
if(newValue == '1')
{
desiredCharacter ='1';
}
}
finally we convert the modified characters back into a string like so:
String rebuiltString = new String(characters);
I am sure there are more efficient ways to do this.
Well, if you want to set a specific bit in a number:
To turn it on:
number |= (1 << pos)
if pos = 4: (1<<pos) = 00000000 00000000 00000000 00010000
To turn it off:
number &= ~(1 << pos)
if pos = 4: ~(1<<pos) = 11111111 11111111 11111111 11101111
where pos is the position of the bit (with 0 being the low order bit, and 64 being the high order bit).