evenBitParity - returns 1 if an odd number of the even-indexed bits of x are 0's (bit 0 of x is the 1's place) - bit

The is a bit manipulation problem.
/*
evenBitParity - returns 1 if an odd number of the even-indexed bits of x are 0's (bit 0 of x is the 1's place)
Examples:
evenBitParity(0) = 0 (16 zero even-indexed bits),
evenBitParity(2) = 0 (16 zero even-indexed bits, bit 1 is non-zero but not even-indexed)
evenBitParity(3) = 1 (15 zero even-indexed bits),
evenBitParity(5) = 0 (14 zero-indexed bits),
evenBitParity(7) = 0
evenbitParity(21) = 1
Legal ops: ! ~ & ^ | + << >>
Max ops: 15
Rating: 4
*/
int evenBitParity(int x) {
}
I try to solve it with the code below, but the operations are too many so I didn't get full credit. Can anyone give a better solution for this?
Thanks a lot!
int masker = (0x55 << 8)+0x55;
masker = (masker<<16)+masker;
x = x&masker;
x = x ^ (x >> 1);
x = x ^ (x >> 2);
x = x ^ (x >> 4);
x = x ^ (x >> 8);
x = x ^ (x >> 16);
return x&1;

A better solution:
int masker = (0x55 << 8)+0x55;
y = (x >> 16) & masker;
x = x&masker;
x = x ^ y;
x = x ^ (x >> 1);
x = x ^ (x >> 2);
x = x ^ (x >> 4);
x = x ^ (x >> 8);
return x&1;

Try this one for your self. The improved version is ebp2();
You didn't need to use a mask and all that. Simply omit the first shift to ignore all odd-indexed bits.
I think I deserve a beer or at least a coffee for my effort.
int main(int argc, char** argv){
int x;
x = 0;
printf("%d\t%d\t%d\n", x, ebp1(x), ebp2(x));
x = 2;
printf("%d\t%d\t%d\n", x, ebp1(x), ebp2(x));
x = 3;
printf("%d\t%d\t%d\n", x, ebp1(x), ebp2(x));
x = 5;
printf("%d\t%d\t%d\n", x, ebp1(x), ebp2(x));
x = 7;
printf("%d\t%d\t%d\n", x, ebp1(x), ebp2(x));
x = 21;
printf("%d\t%d\t%d\n", x, ebp1(x), ebp2(x));
}
int ebp1(int x){
int masker = (0x55 << 8)+0x55;
masker = (masker<<16)+masker;
x = x&masker;
x = x ^ (x >> 1);
x = x ^ (x >> 2);
x = x ^ (x >> 4);
x = x ^ (x >> 8);
x = x ^ (x >> 16);
return x&1;
}
int ebp2(int x){
x = x ^ (x >> 2);
x = x ^ (x >> 4);
x = x ^ (x >> 8);
x = x ^ (x >> 16);
return x&1;
}

Related

The Two Water Jug Puzzle

I am trying to solve the two WATER JUG PUZZLE using euclidean algorithm and Diophantine equation.
let gcd(m,n) = g
using euclidean aldortihm we get X' and Y' such that mX' + nY' = g
for mX + nY = d
if d%g!= 0 no solution exists
else i made X' as X' / g * d and Y' as Y' / g * d
this is one solution for mX + nY = d
now multiple solutions by m ( X' + ( k * n / g ) ) + n ( Y' - ( m * k / g ) ) = d
i just needed to output the SUM OF NO. OPERATIONS
so, i think of the solution as X' + Y' + k * ( n - m ) / g and i want to minimise this
my code below for the same (its giving wrong answers...)
int X, Y;
int gcd(int a, int b)
{
if (b == 0)
{
X = 1;
Y = 0;
return a;
}
int g = gcd(b, a % b);
int X1 = Y;
int Y1 = X - (a / b) * Y;
X = X1;
Y = Y1;
return g;
}
cin >> m >> n >> d;
int g = gcd(n, m);
if (d % g)
cout << -1 << endl;
else
{
X = X / g * d;
Y = Y / g * d;
int ans = X + Y;
int mn = ans;
while (ans > 0)
{
ans += ((m - n) / g);
mn = min(ans, mn);
}
while (ans < 10000)
{
ans += ((n - m) / g);
mn = min(ans, mn);
}
cout << mn << endl;
}

Finding inverse operation to George Marsaglia's XorShift RNG

Abstract
Hi, suppose you have 128 bit automata (represented by four 32 bit words X, Y, Z, W) that changes it's state according to a following rule:
X = ...
Y = ...
Z = ...
W = ...
void next()
{
var t = X ^ (X << 11);
X = Y;
Y = Z;
Z = W;
W = W ^ (W >> 19) ^ (t ^ (t >> 8));
}
^ - denotes binary XOR operation
<< - denotes binary shift left operation
>> - denotys binary shift right operation
It is guaranteed that the above automata generates no collisions i.e. each state is a result of one (and only one) previous state. It is also guaranteed that the above state machine produces 2^128 unique states.
Question
For any given state (X,Y,Z,W) produce inverse to next, (i.e. prev) operation that would revert the state to previous one.
In other words, if you have the following state (X=1, Y=2, Z=3, W=4) and will call next, the state will change to (X=2, Y=3, Z=4, W=2061), it is supposed that after calling prev the state should be equal again to (X=1, Y=2, Z=3, W=4).
P.S.
The next operation is one of the implementations to XorShift pseudorandom number generators that was discovered by George Marsaglia
https://en.wikipedia.org/wiki/Xorshift
The inverse to this operation would be very useful in general, consider the implications of Guid.Next(...), Guid.Prev(...) availability
Edit
I have somewhat improved Niklas B.'s original answer and ported result to C#, so here's the final piece of code, hope someone will benefit from Random.Next() and Random.Prev() operations:
public class Xor128
{
public UInt32 X { get; set; }
public UInt32 Y { get; set; }
public UInt32 Z { get; set; }
public UInt32 W { get; set; }
public Xor128()
{
}
public Xor128(UInt32 x, UInt32 y, UInt32 z, UInt32 w)
{
X = x;
Y = y;
Z = z;
W = w;
}
//private UInt32 UnXorShl(UInt32 x, Int32 shift)
//{
// for (var i = shift; i < 32; i <<= 1) {
// x ^= x << i;
// }
// return x;
//}
//private UInt32 UnXorShr(UInt32 x, Int32 shift)
//{
// for (var i = shift; i < 32; i <<= 1) {
// x ^= x >> i;
// }
// return x;
//}
//public UInt32 Prev()
//{
// var t = UnXorShr(W ^ Z ^ (Z >> 19), 8);
// W = Z;
// Z = Y;
// Y = X;
// X = UnXorShl(t, 11);
// return W;
//}
public UInt32 Prev()
{
var t = W ^ Z ^ (Z >> 19);
t ^= t >> 8;
t ^= t >> 16;
W = Z;
Z = Y;
Y = X;
t ^= t << 11;
t ^= t << 22;
X = t;
return W;
}
public UInt32 Curr()
{
return W;
}
public UInt32 Next()
{
UInt32 t = X ^ (X << 11);
X = Y;
Y = Z;
Z = W;
return W = W ^ (W >> 19) ^ (t ^ (t >> 8));
}
}
btw. Here's a swift version:
public class Xor128 {
public var X: UInt32
public var Y: UInt32
public var Z: UInt32
public var W: UInt32
public convenience init(uuid: uuid_t) {
let xa = (UInt32(uuid.0 ) << 24)
let xb = (UInt32(uuid.1 ) << 16)
let xc = (UInt32(uuid.2 ) << 8 )
let xd = (UInt32(uuid.3 ) << 0 )
let ya = (UInt32(uuid.4 ) << 24)
let yb = (UInt32(uuid.5 ) << 16)
let yc = (UInt32(uuid.6 ) << 8 )
let yd = (UInt32(uuid.7 ) << 0 )
let za = (UInt32(uuid.8 ) << 24)
let zb = (UInt32(uuid.9 ) << 16)
let zc = (UInt32(uuid.10) << 8 )
let zd = (UInt32(uuid.11) << 0 )
let wa = (UInt32(uuid.12) << 24)
let wb = (UInt32(uuid.13) << 16)
let wc = (UInt32(uuid.14) << 8 )
let wd = (UInt32(uuid.15) << 0)
self.init(
x: xa + xb + xc + xd,
y: ya + yb + yc + yd,
z: za + zb + zc + zd,
w: wa + wb + wc + wd
)
}
public convenience init(uuid: UUID) {
self.init(uuid: uuid.uuid)
}
public init(x: UInt32, y: UInt32, z: uint32, w: UInt32) {
X = x
Y = y
Z = z
W = w
}
#discardableResult
public func next() -> UInt32 {
let t = X ^ (X << 11);
X = Y;
Y = Z;
Z = W;
W = W ^ (W >> 19) ^ (t ^ (t >> 8))
return W;
}
public var curr: UInt32 {
return W
}
#discardableResult
public func prev() -> UInt32 {
var t = W ^ Z ^ (Z >> 19);
t ^= t >> 8;
t ^= t >> 16;
W = Z;
Z = Y;
Y = X;
t ^= t << 11;
t ^= t << 22;
X = t;
return W;
}
}
The basic building block you need is an algorithm to reverse the XOR with left shift operation f(x) = x ^ (x << s) for some s > 0. Given f(x), you already know the lower s bits of x directly.
You can reconstruct the rest of the bits iteratively from low to high, because you already know at each point the two bits that have been XORed to get the bit of f(x). Here's an example in Python:
def reverse_xor_lshift(y, shift, w=32):
x = y & ((1<<shift) - 1)
for i in range(w - shift):
x |= (1 if bool(x & (1<<i)) ^ bool(y & (1<<(shift+i))) else 0)<<(shift+i)
return x
Now the rest becomes rather easy. Note that I'm reusing the left shift reversal for the right shift analogue:
def reverse_bin(x, w=32):
return int(bin(x)[2:].rjust(w, '0')[::-1], 2)
def reverse_xor_rshift(y, shift, w=32):
# for simplicity, we just reuse reverse_xor_lshift here
return reverse_bin(reverse_xor_lshift(reverse_bin(y), shift))
def forward(X, Y, Z, W):
t = (X ^ (X << 11)) & 0xffffffff
X = Y
Y = Z
Z = W
W = W ^ (W >> 19) ^ (t ^ (t >> 8))
return (X, Y, Z, W)
def backward(X, Y, Z, W):
t = reverse_xor_rshift(W ^ Z ^ (Z >> 19), 8)
return (reverse_xor_lshift(t, 11), X, Y, Z)
backward is the function that reverses the state transition. Some random testing:
import random
for _ in range(1000):
X, Y, Z, W = [random.randint(0,2**32-1) for _ in range(4)]
assert backward(*forward(X,Y,Z,W)) == (X, Y, Z, W)
Seems to work.
For Y, Z and W, we can easily reverse it. For X, we need to make some observations:
W' = W ^ (W >> 19) ^ (t ^ (t >> 8)), -> t ^ (t >> 8) = W' ^ (W ^ (W >> 19))
So, now, we have t ^ (t >> 8) = W' ^ (W ^ (W >> 19)) = a
t = X ^ (X << 11)
-> t ^ (t >> 8) = X ^ (X << 11) ^ ((X ^ (X <<11)) >> 8)
= X ^ (X << 11) ^ (X >> 8) ^ (X << 3)
Denoting each bit of X as x0, x1, x2, ... x31, and each bit of a as a0, a1, ... we can form following equation system:
x0 ^ x8 = a0
x1 ^ x9 = a1
.....
Or, equivalent to:
(x0 + x8) % 2 = a0
(x1 + x9) % 2 = a1
....
Which we can easily solve by applying Gaussian elimination.

Simplify the inverse of Z = X ^ (X << Y) function

I'm having difficulty with simplifying the following function into several several atomic binary operations, it feels like it's possible however I'm unable to do it, I'm scratching my head for few hours already:
public UInt32 reverse_xor_lshift(UInt32 y, Int32 shift)
{
var x = y & (UInt32)((1 << shift) - 1);
for (int i = 0; i < (32 - shift); i++) {
var bit = ((x & (1 << i)) >> i) ^ ((y & (1 << (shift + i))) >> (shift + i));
x |= (UInt32)(bit << (shift + i));
}
return x;
}
what the function does is just it computes the inverse of the Z = X ^ (X << Y), in other words reverse_xor_lshift(Z, Y) == X
You can inverse it with much fewer operations, though in a harder to understand way, by using the same technique as used in converting back from grey code:
Apply the transformation z ^= z << i where i starts at shift and doubles every iteration.
In pseudocode:
while (i < 32)
x ^= x << i
i *= 2
This works because in the first step, you xor the lowest bits (unaffected) by the place where they were "xored in", thus "xoring them out". Then the part that has been changed to the original is twice as wide. The new number is then of the form x ^ (x << k) ^ (x << k) ^ (x << 2k) = x ^ (x << 2k) which is the same thing again but with twice the offset, so the same trick will work again, decoding yet more of the original bits.

Bitwise integer cube root algorithm

Here is a simple way to calculate an integer square root:
int isqrt(int num)
{
int root=0;
int b = 0x8000;
int a=0, c=0;
while (b) {
c = a|b;
if (c*c <= num)
a |= b;
b >>= 1;
}
}
Ingeniously (thanks Wikipedia), this can be optimised like this:
int sqrt(short num)
{
int op = num;
int res = 0;
int one = 1 << 30;
while (one > op)
one >>= 2;
while (one != 0) {
if (op >= res + one) {
op -= res + one;
res = (res >> 1) + one;
}
else
res >>= 1;
one >>= 2;
}
return res;
}
My question: Can a similarly optimised algorithm be written for an integer cube root? (This is to be run on a small microcontroller which prefers not to do multiplications)
According to this SO question and to the answer marked, from the Hacker's Delight book you can find this implementation:
int icbrt2(unsigned x) {
int s;
unsigned y, b, y2;
y2 = 0;
y = 0;
for (s = 30; s >= 0; s = s - 3) {
y2 = 4*y2;
y = 2*y;
b = (3*(y2 + y) + 1) << s;
if (x >= b) {
x = x - b;
y2 = y2 + 2*y + 1;
y = y + 1;
}
}
return y;
}
This is an (extreme) C# optimized version of the Hacker's Delight code, as mentioned by others.
For reference (on my pc): Math.Sqrt takes about 35 ns, cbrt < 15 ns.
Multiplications by small numbers are used, but it's easy to replace them with shifts and
adds. For example the largest multipication (last line):
"12 * z" ==> "(z << 3) + (z << 2)"
It's difficult to judge whether the size of the code is acceptable for a small microcontroller.
First step: A binary search, the "if" statements, large values ( >= 1u << 24 ) are found relatively faster, small values ( < 64 ) are handled during the search.
Second step: A jump into the unrolled loop, the "labels".
private static uint cbrt(uint x)
{
uint y = 2, z = 4, b = 0;
if (x < 1u << 24)
if (x < 1u << 12)
if (x < 1u << 06)
if (x < 1u << 03)
return x == 0u ? 0u : 1u;
else
return x < 27u ? 2u : 3u;
else
if (x < 1u << 09) goto L8; else goto L7;
else
if (x < 1u << 18)
if (x < 1u << 15) goto L6; else goto L5;
else
if (x < 1u << 21) goto L4; else goto L3;
else
if (x >= 1u << 30) goto L0;
else
if (x < 1u << 27) goto L2; else goto L1;
L0: x -= 1u << 30; if (x >= 19u << 27)
{ x -= 19u << 27; z = 9; y = 3; } goto M0;
L1: x -= 1u << 27; if (x >= 19u << 24)
{ x -= 19u << 24; z = 9; y = 3; } goto M1;
L2: x -= 1u << 24; if (x >= 19u << 21)
{ x -= 19u << 21; z = 9; y = 3; } goto M2;
L3: x -= 1u << 21; if (x >= 19u << 18)
{ x -= 19u << 18; z = 9; y = 3; } goto M3;
L4: x -= 1u << 18; if (x >= 19u << 15)
{ x -= 19u << 15; z = 9; y = 3; } goto M4;
L5: x -= 1u << 15; if (x >= 19u << 12)
{ x -= 19u << 12; z = 9; y = 3; } goto M5;
L6: x -= 1u << 12; if (x >= 19u << 09)
{ x -= 19u << 09; z = 9; y = 3; } goto M6;
L7: x -= 1u << 09; if (x >= 19u << 06)
{ x -= 19u << 06; z = 9; y = 3; } goto M7;
L8: x -= 1u << 06; if (x >= 19u << 03)
{ x -= 19u << 03; z = 9; y = 3; } goto M8;
M0: y *= 2; z *= 4; b = 3 * y + 3 * z + 1 << 24;
if (x >= b) { x -= b; z += 2 * y + 1; y += 1; }
M1: y *= 2; z *= 4; b = 3 * y + 3 * z + 1 << 21;
if (x >= b) { x -= b; z += 2 * y + 1; y += 1; }
M2: y *= 2; z *= 4; b = 3 * y + 3 * z + 1 << 18;
if (x >= b) { x -= b; z += 2 * y + 1; y += 1; }
M3: y *= 2; z *= 4; b = 3 * y + 3 * z + 1 << 15;
if (x >= b) { x -= b; z += 2 * y + 1; y += 1; }
M4: y *= 2; z *= 4; b = 3 * y + 3 * z + 1 << 12;
if (x >= b) { x -= b; z += 2 * y + 1; y += 1; }
M5: y *= 2; z *= 4; b = 3 * y + 3 * z + 1 << 09;
if (x >= b) { x -= b; z += 2 * y + 1; y += 1; }
M6: y *= 2; z *= 4; b = 3 * y + 3 * z + 1 << 06;
if (x >= b) { x -= b; z += 2 * y + 1; y += 1; }
M7: y *= 2; z *= 4; b = 3 * y + 3 * z + 1 << 03;
if (x >= b) { x -= b; z += 2 * y + 1; y += 1; }
M8: y *= 2; return x <= 3 * y + 12 * z ? y : y + 1;
}

Bit Reversal using bitwise

I am trying to do bit reversal in a byte. I use the code below
static int BitReversal(int n)
{
int u0 = 0x55555555; // 01010101010101010101010101010101
int u1 = 0x33333333; // 00110011001100110011001100110011
int u2 = 0x0F0F0F0F; // 00001111000011110000111100001111
int u3 = 0x00FF00FF; // 00000000111111110000000011111111
int u4 = 0x0000FFFF;
int x, y, z;
x = n;
y = (x >> 1) & u0;
z = (x & u0) << 1;
x = y | z;
y = (x >> 2) & u1;
z = (x & u1) << 2;
x = y | z;
y = (x >> 4) & u2;
z = (x & u2) << 4;
x = y | z;
y = (x >> 8) & u3;
z = (x & u3) << 8;
x = y | z;
y = (x >> 16) & u4;
z = (x & u4) << 16;
x = y | z;
return x;
}
It can reverser the bit (on a 32-bit machine), but there is a problem,
For example, the input is 10001111101, I want to get 10111110001, but this method would reverse the whole byte including the heading 0s. The output is 10111110001000000000000000000000.
Is there any method to only reverse the actual number? I do not want to convert it to string and reverser, then convert again. Is there any pure math method or bit operation method?
Best Regards,
Get the highest bit number using a similar approach and shift the resulting bits to the right 33 - #bits and voila!
Cheesy way is to shift until you get a 1 on the right:
if (x != 0) {
while ((x & 1) == 0) {
x >>= 1;
}
}
Note: You should switch all the variables to unsigned int. As written you can have unwanted sign-extension any time you right shift.
One method could be to find the leading number of sign bits in the number n, left shift n by that number and then run it through your above algorithm.
It's assuming all 32 bits are significant and reversing the whole thing. You COULD try to make it guess the number of significant bits by finding the highest 1, but that isn't necessarily accurate so I'd suggest you modify the function so it takes a second parameter indicating the number of significant bits. Then after reversing the bits just shift them to the right.
Try using Integer.reverse(int x);

Resources