0

I'm trying to use the bit operation << in my code below. Here is my tinyfp2int function that does bunch of bit operations given a binary formatted unsigned character type.

#include <stdio.h>
#define TMin 0b1<<31
typedef unsigned char tinyfp;

int tinyfp2int(tinyfp x) 
{

    int sign = (x>>7);
    int result = 0;
    int exp[4];
    int exponent=0;
    int temp=0;

    //get the exponent
    int i=0;
    for(i=0;i<4;i++){
        exp[3-i] = (x>>(3+i))%2;
        exponent += exp[3-i]<<i;
    }
    exponent -= 7;

    //now bitwise operations.
    result += (1<<exponent); //ERROR!!!
    printf("exponent is %d ,shifting 1 with exponent is %d\n",exponent,1<<exponent); // I put this code in because there was a dummy value was inserted on the line above

    if(sign>0)
        return -result;
    else
        return result;
    }

And finally, this is my main function.

void main(){
tinyfp2int(0b00011110);
printf("%d\n",(1<<-4));
}

However, if I run this code, the result is

exponent is -4 ,shifting 1 with exponent is 268435456
0

I really don't understand why 1<<-4 operation in the main function works, whileas the 1<<-4 operation in the tinyfp2int function keeps returning a dummy value. I would really appreciate any explanation. Thanks in advance!

  • 1
    Shifting outside of range 0..31 is undefined (IIRC) – user202729 Mar 26 '18 at 06:07
  • 1
    [See this](https://stackoverflow.com/questions/9860538/unexpected-c-c-bitwise-shift-operators-outcome). And [this](https://stackoverflow.com/questions/4945703/left-shifting-with-a-negative-shift-count). – user202729 Mar 26 '18 at 06:08
  • 1
    In this case, the compiler is both overly-smart and hardcode-the-wrong-constant. Anyway, don't expect anything from undefined behavior. – user202729 Mar 26 '18 at 06:11

0 Answers0