> =" operators and 20 operations So, I have a purpose that I have to encode...">

Implementing a logical shift to the right using only "~ & ^ | + << >> =" operators and 20 operations

So, I have a purpose that I have to encode a function in c that uses only the bitwise operations ~, and, ^, |, +, <, →, and =. I should use only 20 operations. And I am not allowed to use control structures such as if-else, for, while, switch or anything else that exc exc code in conditional blocks. Also, the casting type is also absent , and bytes that are not declared in the function header (which is provided to me) are limited to 1 byte or 8-bit values; so i have hex from 0 to ff.

The function that I have to code is a logical shift to the right. Therefore, instead of bits filled with a signed bit, they should be filled with 0

This is what I did:

int logicalShift(int x, int n) {
    int op=0xFFFFFFFF;
    int tcn=(~n+1);
    int sizeshift=0x20 & tcn;
    op=(op<<sizeshift);
    return ((x>>n) + (op));
}

This is what I expect to get (for x = 0x80000000 and n = 0x01) I expect to get 0x40000000, which is 1073741824 in decimal. This is what I get. However (for x = 0x80000000 and n = 0x0 I expect to get 0x80000000, but I get 0x7fffffff, and this is my answer minus a little. I could add a little, but it messed up the first answer. So, what I'm doing wrong is that I have one case, but not another.I also tried.

int logicalShift(int x, int n) {
    int op=0xFFFFFFFF;
    int tcn=(~n+1);
    int sizeshift=0x20 & tcn;
    op=(op<<sizeshift);
    return ((x>>n) + (op  ^ ~n));
}

, XOR , 1 0, , (aka) 0x7fffffff, 2 . . , , ?

+4
2

- , . , , . :

  • , n , ANDed .
  • n .
  • .

AND , , . 0.

, . .

+3

, (x >> n) == (x >>> n). , , : (x & 0x7FFFFFFF) >> n | (0x40000000 >> (n - 1)).

, , . if, . .

int signBit1 = (x & 0x7FFFFFFF) >> n | (0x40000000 >> (n - 1));
int signBit0 = x >> n;
var signBitIsolated = x & 0x80000000; // either 0 or 0x80000000
var signMask = signBitIsolated >> 31; //either 0 or 0xFFFFFFFF
var combined = (signBit0 & ~signMask) | (signBit1 & signMask);
return combined;

, all-zeros all-ones / .

, , . , .

0

All Articles