0

I am working on a function, sign, that returns 1 if a given int is positive, 0 if zero and -1 if negative. I am only allowed to use the following operations: ! ~ & ^ | + << >>. So far, I have tried an array of things, and have gotten extremely close but don't know how to distinguish between a 1 and -1.

int sign(int x) {
    return (((x >> 31) & 1) ^ (!x));
}

Am I missing something here? I am pulling my hair out trying to figure this out.

enzo
  • 9,861
  • 3
  • 15
  • 38
  • 1
    With that sort of arbitrary restriction on what operators you can use, is this homework? – Shawn Nov 30 '21 at 04:17
  • Your expression has mismatched `(` `)` and won't even compile – abelenky Nov 30 '21 at 04:17
  • 1
    @Shawn Yes it is,@abelenky I have updated the code so that it will compile – CalebDunham Nov 30 '21 at 04:19
  • Do you know if you’re allowed to rely on the implementation-defined behaviour of sign extension, i.e. `(x >> 31) == -1` for any negative 32-bit integer `x`? – Ry- Nov 30 '21 at 04:23
  • `a - b` is the same as `a + -b`, and `-b` is the same as `~b + 1`. – o11c Nov 30 '21 at 04:24
  • I am not allowed to rely on implementation with == or - sadly. I was able to get as far as a + ~b + 1, however, I am struggling with how to use it. I am thinking there something like (endBit & 1) ^ (!0) | ~(endBit &1) ^ (!0) | x ^ 0 where the first part checks positive, negative, and zero, however that doesn't work on in practice – CalebDunham Nov 30 '21 at 04:33

1 Answers1

1
#include <stdio.h>
#include <limits.h> // For CHAR_BIT

int sign(int x)
{
    // sizeof * CHAR_BIT to calculate number of bits in int
    // if run on a non-32-bit system
    return !!x | x >> (sizeof(x)*CHAR_BIT-1);
     // Allowed: ! ~ & ^ | + << >>
}

int main(void) {
    int a = 6;
    int b = 0;
    int c = -10;
    
    printf("%d %d %d\n", sign(a), sign(b), sign(c));
    
    return 0;
}

Output

Success #stdin #stdout 0s 5392KB
1 0 -1
abelenky
  • 63,815
  • 23
  • 109
  • 159