-2

I'm writing code to translate machine code. readFiveBytes is inside of a loop and supposed to take one byte at a time and place each byte into its correct place and return an address in the end.

void readFiveBytes(int c) {
    if (counter != 0) {
        currentIns = currentIns | (c << (counter * 4));
        printf("reading byte: %X; address: %08X; counter: %d; type: 5\n",c, currentIns, counter);
        counter = counter - 2;
    } else {
        currentIns = currentIns | c;
        printType3(currentIns);
        printf("reading byte: %X; address: %08X; counter: %d; type: 5\n",c, currentIns, counter);
        currentIns = 0x00000000000000;
        isFinishReading = true;
    }
}   

the output is

reading byte: 71; address: 00000071; counter: 8; type: 5
reading byte: 26; address: 26000071; counter: 6; type: 5
reading byte: 0; address: 26000071; counter: 4; type: 5
reading byte: 0; address: 26000071; counter: 2; type: 5
reading byte: 0; address: 26000071; counter: 0; type: 5 

I'm wondering why the first byte has not been shifted to the most left? (It seems like second one is working well)

user3397656
  • 57
  • 1
  • 10
  • what if `counter > CHAR_BIT`? – Iharob Al Asimi Feb 07 '15 at 18:05
  • 5
    "bit shifting in c not working properly" – gotta love these " not working" questions… surely it **is** working? At most *you* can't use it properly… – The Paramagnetic Croissant Feb 07 '15 at 18:07
  • 2
    This type of function is the reason why people say that global variables are bad. This function doesn't even do anything by itself, it's the body of a loop that has been forcefully removed from its rightful place, and now communicates through some globals in a way that is not obvious and, from the looks of it, broken. Don't even fix this function, replace it by something better. – harold Feb 07 '15 at 18:16
  • it is a great function – user3397656 Feb 08 '15 at 02:43

1 Answers1

1

Shifting the bit width or more is undefined behavior.

The first pass, counter = 8 attempts currentIns = currentIns | (c << 32);. Assuming currentIns is a 32-bit integer, this is undefined behavior.

The typical undefined behavior in this case is only a shift of (counter * 4)%32 occurs. With counter = 8, this is a shift of 0.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256