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
Class & Function Names Highlighting in Vim
Generate Sha Hash in C++ Using Openssl Library
Converting Data from Glreadpixels() to Opencv::Mat
Can a Cast Operator Be Explicit
Checking If an Iterator Is Valid
Making a Template Parameter a Friend
Determine Path to Registry Key from Hkey Handle in C++
How Does a 32 Bit Processor Support 64 Bit Integers
Does Std::Stack Expose Iterators
Boost.Asio-Based Http Client Library (Like Libcurl)
How to Alpha Blend Rgba Unsigned Byte Color Fast
Does "Std::Size_T" Make Sense in C++
Why Aren't Static Const Floats Allowed
"If" Argument Evaluation Order
How to Replace All Instances of a String with Another String