Can I turn unsigned char into char and vice versa?

后端 未结 6 2112
死守一世寂寞
死守一世寂寞 2020-11-29 20:03

I want to use a function that expects data like this:

void process(char *data_in, int data_len);

So it\'s just processing some bytes really

6条回答
  •  没有蜡笔的小新
    2020-11-29 20:59

    You can pass a pointer to a different kind of char, but you may need to explicitly cast it. The pointers are guaranteed to be the same size and the same values. There isn't going to be any information loss during the conversion.

    If you want to convert char to unsigned char inside the function, you just assign a char value to an unsigned char variable or cast the char value to unsigned char.

    If you need to convert unsigned char to char without data loss, it's a bit harder, but still possible:

    #include 
    
    char uc2c(unsigned char c)
    {
    #if CHAR_MIN == 0
      // char is unsigned
      return c;
    #else
      // char is signed
      if (c <= CHAR_MAX)
        return c;
      else
        // ASSUMPTION 1: int is larger than char
        // ASSUMPTION 2: integers are 2's complement
        return c - CHAR_MAX - 1 - CHAR_MAX - 1;
    #endif
    }
    

    This function will convert unsigned char to char in such a way that the returned value can be converted back to the same unsigned char value as the parameter.

提交回复
热议问题