Bit circular shift - java

I am currently learning on bit-wise operations, and i am tasked to do a left rotate of 4-bit integer.
My code for a 4bit left rotate is
private static int BITS_IN_INTEGER = 4;
private static int leftRotate(int x, int n) {
return (x << n) | (x >> (BITS_IN_INTEGER - n));
}
I want to make a 4-bit circular shift to maintain as a 4-bit after rotating but can't seem to understand how it works.
Example: 10 (1010) after left rotate by 1 bit will give me 5 (0101) but it gives me a value of 21 which is more than my 4-bit.
Any help to make me understand this problem will be much appreciated!

If I understood you correctly, you want to
emulate integers with BITS_IN_INTEGER many bits instead of 32 bits.
do a rotation on such an emulated integer
Currently you can do a rotation, but the upper bits of the actual int which are not part of the emulated int can end up in something other than 0. Example:
intput x
0000 0000 0000 0000 0000 0000 0000 1100
|____|___, emulated int
result of rotating left by n=2 | |
0000 0000 0000 0000 0000 0000 0011 0011
As we can see, all we have to do is setting the bits above the emulated int (that is the 32 - BITS_IN_INTEGER upper bits) to zero. To this end, we use a logical "and" (&). We need a mask that has 0 on the bits we want to set to zero (anything & 0 is always 0) and a 1 on the bits we want to keep (anything & 1 is always anything).
0...0 0011 0011 ← the result from before
& 0...0 0000 1111 ← a mask
——————————————————
0...0 0000 0011 ← the masked result where unused bits are 0
To generate a mask of the form 0...01...1 with BITS_IN_INTEGER many 1s we can use (1 << BITS_IN_INTEGER) - 1. The - 1 converts 10000 into 01111.
static int BITS_IN_INTEGER = 4;
static int INTEGER_MASK = (1 << BITS_IN_INTEGER) - 1;
static int leftRotate(int x, int n) {
return INTEGER_MASK & ((x << n) | (x >>> (BITS_IN_INTEGER - n)));
}

This is a javascript implementation of leftRotate() and rightRotate(), based on the above Answer from Socowi (thank you!)
I needed to emulate a simple compass with 90º degree rotations in both left (counter-clockwise) and right (clockwise) directions (not a real compass, just a funny problem).
So instead of messing up the code by storing the previous orientation and using * if / else * or * switch *, I came up with the idea that a circular-shift or bit-rotation would be much more clean, efficient, and elegant of course.
However, I had the same problem about limiting the mask to 4 bits. Thanks to the above solution I was able to do it! ;)
So assuming the following:
- North = 1 = 0001
- West = 2 = 0010
- South = 4 = 0100
- East = 8 = 1000
When I need to turn 90º from North to -> West I call leftRotate() and so on until I get to the same point again (North).
The same applies in reverse, if turning 90º from North to -> East I call rightRotate(), and then again to turn South, and so on.
Here is the snippet, hope it helps:
const BITS_IN_INTEGER = 4;
const INTEGER_MASK = (1 << BITS_IN_INTEGER) - 1;
// this function rotates to left (counter clockwise) 1,2,4,8...1,2,4,8
function leftRotate(x, n) {
return INTEGER_MASK & ((x << n) | (x >>> (BITS_IN_INTEGER - n)));
}
// this function rotates to right (clockwise) 1,8,4,2...1,8,4,2
function rightRotate(x, n) {
return INTEGER_MASK & ((x << (BITS_IN_INTEGER - n)) | (x >>> n));
}
// Lets rotate:
console.log('--- Rotate to left (counter clockwise) 1,2,4,8...1,2,4,8...1:')
let value = 1;
for (let i = 0; i < 8; i++) {
console.log(value);
value = leftRotate(value, 1);
}
console.log('-- Rotate to right (counter clockwise) 1,8,4,2...1,8,4,2...1:')
for (let i = 0; i < 8; i++) {
console.log(value);
value = rightRotate(value, 1);
}

Related

Push 4 bits into an int in java

For an implementation of a SPN crypografic feature (studies related) I'm trying to push 4bits into an int.
I can pinpoint the mistake, but I don't know how to fix it (might stared too long at it for now).
private int applySBox(int a, boolean inverse, boolean verbose) {
// split int (16 bit) into parts of 4 bit keeping the right order
int[] parts = new int[4];
for(int i = 0; i < 4; i++) {
parts[4 - i - 1] = a & 0b1111;
a = a >> 4;
}
// Apply the SBox to each 4 bit
// E.g. 1101 traverse (enc) = 1001, inverse (dec) = 0010
for(int i = 0; i < 4; i++) {
if(inverse) {
parts[i] = sbox.inverse(parts[i]);
} else {
parts[i] = sbox.traverse(parts[i]);
}
}
int result = 0;
// put back together
for(int i = 0; i < 4; i++) {
result = parts[i] & 0b1111;
// TODO: Reassigning does not help here, needs shift and &
result = result << 4;
}
return result;
}
Before the SBox I might get a value of 1100111011001111 as cipher text.
In the split portion I get something like this:
Fragment[0]: 0001100011110000
Round Value: 0001100011110000
Current key: 1101011000111111
New r Value: 1100111011001111
---
Before SBox: 1100_1110_1100_1111
Part[0] before SBox: 1100
Part[1] before SBox: 1110
Part[2] before SBox: 1100
Part[3] before SBox: 1111
Part[0] after SBox: 1011
Part[1] after SBox: 0000
Part[2] after SBox: 1011
Part[3] after SBox: 0101
I know this is correct based on the defintion of the SBox I have to use.
This would mean, that in order to get the result I have to push parts 0 to 3 pack into one int 1011_0000_1011_0101 and it would be the correct result.
I can clearly see that it won't work because I always overwrite the result with result = parts[i] & 0b1111; I just can't seem to find a fix.
How can I push an int[] array each int with 4 bits worth of data in the order from 0 to 3 into the int result containing 16 bit of data?
If you shift the bits to the left then the rightmost bits fill up with zeros. So then you need to XOR or OR the results into place.
Try and replace
result = parts[i] & 0b1111;
with
result ^= parts[i] & 0b1111;
or
result |= parts[i] & 0b1111;
otherwise you are simply reassigning the value and delete the previous 4 bit blocks.
Do you mean:
result = (result << 4) | parts[i];
or, same thing written differently:
result |= parts[i] << (4 * (4-i));
If so then, yes, you stared too long at the screen and "got square eyes" as they say!
Update: Since OP implies it's OK to lock-in four parts. Here's an untested one-liner for the traverse variant:
return sbox.traverse(a & 0b1111)
| sbox.traverse(a >> 4 & 0b1111) << 4
| sbox.traverse(a >> 8 & 0b1111) << 8
| sbox.traverse(a >> 12 & 0b1111) << 12

Java - Setting a distinct bit of an integer to zero

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)));
}

Right shift operator in java

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.

what does " int pix = (0xff & ((int) first[ij])); " mean?

The following code is part of a working camera app that detects motion and saves preview, painting the moving parts red.
public class RgbMotionDetection implements IMotionDetection {
that detects motion
private static final int mPixelThreshold = 50; // Difference in pixel (RGB)
private static final int mThreshold = 10000; // Number of different pixels
private static int[] mPrevious = null;
private static int mPreviousWidth = 0;
private static int mPreviousHeight = 0;
/**
* {#inheritDoc}
*/
#Override
public int[] getPrevious() {
return ((mPrevious != null) ? mPrevious.clone() : null);
}
protected static boolean isDifferent(int[] first, int width, int height) {
if (first == null) throw new NullPointerException();
if (mPrevious == null) return false;
if (first.length != mPrevious.length) return true;
if (mPreviousWidth != width || mPreviousHeight != height) return true;
int totDifferentPixels = 0;
for (int i = 0, ij = 0; i < height; i++) {
for (int j = 0; j < width; j++, ij++) {
int pix = (0xff & ((int) first[ij]));
int otherPix = (0xff & ((int) mPrevious[ij]));
// Catch any pixels that are out of range
if (pix < 0) pix = 0;
if (pix > 255) pix = 255;
if (otherPix < 0) otherPix = 0;
if (otherPix > 255) otherPix = 255;
if (Math.abs(pix - otherPix) >= mPixelThreshold) {
totDifferentPixels++;
// Paint different pixel red
first[ij] = Color.RED;
}
}
}
I'd like to understand this fully in order to be able to modify.
The line that really puzzles me is:
int pix = (0xff & ((int) first[ij]));
What does it do?
thanks
Dave
Forgive me if I explain something now that you know but I want to make this a self contained answer.
The colors of a pixel can be stored in an integer. An integer in Java consist of four bytes, a color typically (in this context) is represented with four bytes: One byte each for red, green, and blue, the last byte for transparency. The mix of the subpixels on screen results in the observed color.
So the following integer represents a color:
0 0 f f c c a a (Hexadecimal representation)
0000 0000 1111 1111 1100 1100 1010 1010 (Binary representation)
Transp.-- Red------ Green---- Blue----- (Color interpretation)
16764074 (Decimal representation, quite useless here)
In this case the first two bytes (00) represent the transparency, ff the red subpixel, cc the green, aa the blue.
If we want to get only a single part of this, e.g. the blue subpixel, we need a bit mask.
0000 0000 1111 1111 1100 1100 1010 1010 (Binary representation)
& (Binary AND: Return 1 if both bits are 1)
0000 0000 0000 0000 0000 0000 1111 1111 (Bitmask for blue, in hex 0x000000ff)
=
0000 0000 0000 0000 0000 0000 1010 1010
This is the result of the operation in the line you mention, it just uses the shorthand hex interpretation for the mask:
int pix = (0xff & ((int) first[ij]));
As the array first already is an int array the cast of first[ij] is useless.
If you want another part of the pixel, say the green part, you need to shift the mask (or use a hardcoded value) and need to shift back the result:
00ffccaa
&
0000ff00 Hardcoded, alternative: ff << 8
=
0000cc00
Shift the result to the rightmost position within the integer
0000cc00 >> 8 = 000000cc
Similar with 16 and 24 for red resp. transparency.
So the line gives you the value of the blue subpixel of the pixel. This value is in the range of 0..255, as these are the only values possible with eight bits (when interpreted as unsigned byte or stored in a Java int as it is done here; Java bytes are signed and wouldn't use that decimal representation but -128..127); any check for other values is useless here.
I think that here it tries to get the value of the pixel but in a range of 0 to 255, so it uses the mask 0xFF to delete all the bits in a higher position than 8.
But I don't understand why it uses
if (pix < 0) pix = 0;
if (pix > 255) pix = 255;
When the pix variable can't be higher than 255

How to find the largest power of 2 less than the given number

I need to find the largest power of 2 less than the given number.
And I stuck and can't find any solution.
Code:
public class MathPow {
public int largestPowerOf2 (int n) {
int res = 2;
while (res < n) {
res =(int) Math.pow(res, 2);
}
return res;
}
}
This doesn't work correctly.
Testing output:
Arguments Actual Expected
-------------------------
9 16 8
100 256 64
1000 65536 512
64 256 32
How to solve this issue?
Integer.highestOneBit(n-1);
For n <= 1 the question doesn't really make sense. What to do in that range is left to the interested reader.
The's a good collection of bit twiddling algorithms in Hacker's Delight.
Change res =(int)Math.pow(res, 2); to res *= 2; This will return the next power of 2 greater than res.
The final result you are looking for will therefore finally be res / 2 after the while has ended.
To prevent the code from overflowing the int value space you should/could change the type of res to double/long, anything that can hold higher values than int. In the end you would have to cast one time.
You can use this bit hack:
v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v++;
v >>= 1;
Why not use logs?
public int largestPowerOf2(int n) {
return (int)Math.pow(2, Math.floor(Math.log(n) / Math.log(2));
}
log(n) / log(2) tells you the number of times 2 goes into a number. By taking the floor of it, gets you the integer value rounding down.
There's a nice function in Integer that is helpful, numberOfLeadingZeros.
With it you can do
0x80000000 >>> Integer.numberOfLeadingZeros(n - 1);
Which does weird things when n is 0 or 1, but for those inputs there is no well-defined "highest power of two less than n".
edit: this answer is even better
You could eliminate the least significant bit in n until n is a power of 2. You could use the bitwise operator AND with n and n-1, which would eliminate the least significant bit in n until n would be a power of 2. If originally n would be a power of 2 then all you would have to do is reduce n by 1.
public class MathPow{
public int largestPowerOf2(int n){
if((n & n-1) == 0){ //this checks if n is a power of 2
n--; //Since n is a power of 2 we have to subtract 1
}
while((n & n-1) != 0){ //the while will keep on going until n is a power of 2, in which case n will only have 1 bit on which is the maximum power of 2 less than n. You could eliminate the != 0 but just for clarity I left it in
n = n & n-1; //we will then perform the bitwise operation AND with n and n-1 to eliminate the least significant bit of n
}
return n;
}
}
EXPLANATION:
When you have a number n (that is not a power of 2), the largest power of 2 that is less than n is always the most significant bit in n. In case of a number n that is a power of 2, the largest power of 2 less than n is the bit right before the only bit that is on in n.
For example if we had 8 (which is 2 to the 3rd power), its binary representation is 1000 the 0 that is bold would be the largest power of 2 before n. Since we know that each digit in binary represents a power of 2, then if we have n as a number that's a power of 2, the greatest power of 2 less than n would be the power of 2 before it, which would be the bit before the only bit on in n.
With a number n, that is not a power of 2 and is not 0, we know that in the binary representation n would have various bits on, these bits would only represent a sum of various powers of 2, the most important of which would be the most significant bit. Then we could deduce that n is only the most significant bit plus some other bits. Since n is represented in a certain length of bits and the most significant bit is the highest power of 2 we can represent with that number of bits, but it is also the lowest number we can represent with that many bits, then we can conclude that the most significant bit is the highest power of 2 lower than n, because if we add another bit to represent the next power of 2 we will have a power of 2 greater than n.
EXAMPLES:
For example, if we had 168 (which is 10101000 in binary) the while would take 168 and subtract 1 which is 167 (which is 10100111 in binary). Then we would do the bitwise AND on both numbers.
Example:
10101000
& 10100111
------------
10100000
We now have the binary number 10100000. If we subtract 1 from it and we use the bitwise AND on both numbers we get 10000000 which is 128, which is 2 to the power of 7.
Example:
10100000
& 10011111
-------------
10000000
If n were to be originally a power of 2 then we have to subtract 1 from n. For example if n was 16, which is 10000 in binary, we would subtract 1 which would leave us with 15, which is 1111 in binary, and we store it in n (which is what the if does). We then go into the while which does the bitwise operator AND with n and n-1, which would be 15 (in binary 1111) & 14 (in binary 1110).
Example:
1111
& 1110
--------
1110
Now we are left with 14. We then perform the bitwise AND with n and n-1, which is 14 (binary 1110) & 13 (binary 1101).
Example:
1110
& 1101
---------
1100
Now we have 12 and we only need to eliminate one last least significant bit. Again, we then execute the bitwise AND on n and n-1, which is 12 (in binary 1100) and 11 (in binary 1011).
Example
1100
& 1011
--------
1000
We are finally left with 8 which is the greatest power of 2 less than 16.
You are squaring res each time, meaning you calculate 2^2^2^2 instead of 2^k.
Change your evaluation to following:
int res = 2;
while (res * 2 < n) {
res *= 2;
}
Update:
Of course, you need to check for overflow of int, in that case checking
while (res <= (n - 1) / 2)
seems much better.
Here is a recursive bit-shifting method I wrote for this purpose:
public static int nextPowDown(int x, int z) {
if (x == 1)
return z;
return nextPowDown(x >> 1, z << 1);
}
Or shorter definition:
public static int nextPowTailRec(int x) {
return x <= 2 ? x : nextPowTailRec(x >> 1) << 1;
}
So in your main method let the z argument always equal 1. It's a pity default parameters aren't available here:
System.out.println(nextPowDown(60, 1)); // prints 32
System.out.println(nextPowDown(24412, 1)); // prints 16384
System.out.println(nextPowDown(Integer.MAX_VALUE, 1)); // prints 1073741824
A bit late but...
(Assuming 32 bit number.)
n|=(n>>1);
n|=(n>>2);
n|=(n>>4);
n|=(n>>8);
n|=(n>>16);
n=n^(n>>1);
Explanation:
The first | makes sure the original top bit and the 2nd highest top bit are set. The second | makes sure those two, and the next two are, etc, until you potentially hit all 32 bits. Ie
100010101 -> 111111111
Then we remove all but the top bit by xor'ing the string of 1's with that string of 1's shifted one to the left, and we end up with just the one top bit followed by 0's.
public class MathPow {
public int largestPowerOf2 (int n) {
int res = 2;
while (res < n) {
res = res * 2;
}
return res;
}
}
Find the first set bit from left to right and make all other set bits 0s.
If there is only 1 set bit then shift right by one.
I think this is the simplest way to do it.
Integer.highestOneBit(n-1);
public class MathPow
{
public int largestPowerOf2(int n)
{
int res = 1;
while (res <= (n-1)/2)
{
res = res * 2;
}
return res;
}
}
If the number is an integer you can always change it to binary then find out the number of digits.
n = (x>>>0).toString(2).length-1
p=2;
while(p<=n)
{
p=2*p;
}
p=p/2;
If the number is a power of two then the answer is obvious. (just bit shift) if not well then it is also can be achieved by bit shifting.
find the length of the given number in binary representation. (13 in binary = 1101 ; length is 4)
then
shift 2 by (4-2) // 4 is the length of the given number in binary
the below java code will solve this for BigIntegers(so basically for all numbers).
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String num = br.readLine();
BigInteger in = new BigInteger(num);
String temp = in.toString(2);
System.out.println(new BigInteger("2").shiftLeft(temp.length() - 2));
I saw another BigInteger solution above, but that is actually quite slow. A more effective way if we are to go beyond integer and long is
BigInteger nvalue = TWO.pow(BigIntegerMath.log2(value, RoundingMode.FLOOR));
where TWO is simply BigInteger.valueOf(2L)
and BigIntegerMath is taken from Guava.
Simple bit operations should work
public long largestPowerOf2 (long n)
{
//check already power of two? if yes simply left shift
if((num &(num-1))==0){
return num>>1;
}
// assuming long can take 64 bits
for(int bits = 63; bits >= 0; bits--) {
if((num & (1<<bits)) != 0){
return (1<<bits);
}
}
// unable to find any power of 2
return 0;
}
/**
* Find the number of bits for a given number. Let it be 'k'.
* So the answer will be 2^k.
*/
public class Problem010 {
public static void highestPowerOf2(int n) {
System.out.print("The highest power of 2 less than or equal to " + n + " is ");
int k = 0;
while(n != 0) {
n = n / 2;
k++;
}
System.out.println(Math.pow(2, k - 1) + "\n");
}
public static void main(String[] args) {
highestPowerOf2(10);
highestPowerOf2(19);
highestPowerOf2(32);
}
}
if(number>=2){
while(result < number){
result *=2;
}
result = result/ 2;
System.out.println(result);
}

Categories