0

I'm working with 8-bit signed values in c and I'm getting odd behaviour on a raspberry pi 4.

Running the following code on my pc running debian linux:

  typedef char                int8;
  typedef int                 int32;

  int8 example8 = (int8)(127.0 * -0.812);
  
  if (example8 < 0)
    printf("8 Less than 0!!!!\n");
  else if(example8 > 0)
    printf("8 more than 0!!!!\n");
  else
    printf("8 equal 0!!!!\n");


  int32 example32 = (int32)example8;

  if (example32 < 0)
    printf("32 Less than 0!!!!\n");
  else if(example32 > 0)
    printf("32 more than 0!!!!\n");
  else
    printf("32 equal 0!!!!\n");

I get this, which is about what I'd expected:

8 Less than 0!!!!
32 Less than 0!!!!

Running the same code under raspberry pi os on a pi 4 I get this:

8 equal 0!!!!
32 equal 0!!!!

To be clear, all negative values are set to zero while all positive values are fine.

Is this an architecture thing or am I doing something really stupid?

The Gribble
  • 99
  • 1
  • 6
  • 1
    It is implementation defined whether a plain `char` is signed or unsigned. In general you need to be prepared to deal with both variants. Just never use `char`. Instead use the types from `stdint.h` like `uint8_t` or `int8_t` or use `signed char` if you want to handle negative values. – Gerhardh Nov 25 '21 at 14:41
  • 1
    If you want signed 8 bit numbers always use `int8_t`. You should only be using `char` to store characters/strings, never for storing numbers. – Lundin Nov 25 '21 at 14:43

0 Answers0