How to Turn Unsigned Char into Char and Vice Versa

Convert basic_stringunsigned char to basic_stringchar and vice versa

Assuming you want each character in the original copied across and converted, the solution is simple

 u_string u(s.begin(), s.end());
std:string t(u.begin(), u.end());

The formation of u is straight forward for any content of s, since conversion from signed char to unsigned char simply uses modulo arithmetic. So that will work whether char is actually signed or unsigned.

The formation of t will have undefined behaviour if char is actually signed char and any of the individual characters in u have values outside the range that a signed char can represent. This is because of overflow of a signed char. For your particular example, undefined behaviour will generally not occur.

C: Converting unsigned char array to signed int (vice versa)

You could store both int (or unsigned int) and unsigned char array as union. This method is called type punning and it is fully sanitized by standard since C99 (it was common practice earlier, though). Assuming that sizeof(int) == 4:

#include <stdio.h>

union device_buffer {
int i;
unsigned char c[4];
};

int main(int argv, char* argc[])
{
int original = 1054;

union device_buffer db;
db.i = original;

for (int i = 0; i < 4; i++) {
printf("c[i] = 0x%x\n", db.c[i]);
}
}

Note that values in array are stored due to byte order, i.e. endianess.

Casting a char to unsigned char

Since C++14, char if signed must be 2's complement.

Therefore the cast from signed char to unsigned char and vice-versa cannot change the underlying bit pattern.



Related Topics



Leave a reply



Submit