Search code examples
cintegerhexsignedtwos-complement

C : Unable to represent negative values with signed int


I have to write a code for my university project that reads through a binary file and prints out integer values. This is just a small snippet of what I wrote:

signed int ch;
    while ((ch = fgetc(fp)) != EOF) {
            print("Value of n=%d", ch);
    }

However, I can't get it to print out negative values. What I mean is, if the value if 33, 33 is printed, otherwise if the value is -33, 223 is given out.I'm still a beginner and sorry for the bad code. I tried reading the values as hex and then printing out, but that doesn't work. Reading the file with %d also doesn't work. I can get the values correct by converting the number to binary, checking the sign bit, and then doing a 2's complement but I have to return the value properly at a later stage without any operation, so it's not a feasible solution. To sum up, I want to read a negative value, store it, and print it without any other operation. If someone knows what I'm doing wrong, please help! And sorry again if this a beginner question.


Solution

  • However, I can't get it to print out negative values.

    signed int ch;
    while ((ch = fgetc(fp)) != EOF) {
            print("Value of n=%d", ch); 
    }
    

    fgetc(fp) returns a value in the unsigned char range or EOF.
    All non-EOF values would necessarily never be negative1.

    ... the fgetc function obtains that character as an unsigned char converted to an int ... C17dr § 7.21.7.1 2


    If OP wants to read, say 32 bits of binary data, and interpret that as an integer:

    int32_t i;
    while (fread(&i, sizeof i, 1, fp) > 0) {
      printf("%ld\n", (long) i);
    }
    

    1 Pedantic exception. When char size same as int.