Determine the sign of a 32 bit int

后端 未结 8 1517
隐瞒了意图╮
隐瞒了意图╮ 2021-02-08 23:05

Using ONLY:

! ~ & ^ | + << >>

NO LOOPS

I need to determine the sign of a 32 bit integer and I need to return 1 if positive, 0 if 0 and -1 if ne

8条回答
  •  梦毁少年i
    2021-02-08 23:27

    I'm not sure this is the absolute ideal way to do things, but I think it's reasonably portable and at least somewhat simpler than what you had:

    #define INT_BITS 32
    
    int sign(int v) { 
        return (!!v) | -(int)((unsigned int)v >> (INT_BITS-1));
    }
    

提交回复
热议问题