c++ - Converting from signed char to unsigned char and back again? -
i'm working jni , have array of type jbyte, jbyte represented signed char i.e. ranging -128 127. jbytes represent image pixels. image processing, want pixel components range 0 255. therefore want convert jbyte value range 0 255 (i.e. same range unsigned char), calculations on value , store result jbyte again.
how can these conversion safely?
i managed code work, pixel value incremented 30 clamped value 255, don't understand if it's safe or portable:
#define clamp255(v) (v > 255 ? 255 : (v < 0 ? 0 : v)) jbyte pixel = ... pixel = clamp_255((unsigned char)pixel + 30);
i'm interested know how in both c , c++.
this 1 of reasons why c++ introduced new cast style, includes static_cast
, reinterpret_cast
there's 2 things can mean saying conversion signed unsigned, might mean wish unsigned variable contain value of signed variable modulo (the maximum value of unsigned type + 1). if signed char has value of -128 max_char+1
added value of 128 , if has value of -1, max_char+1
added value of 255, done static_cast. on other hand might mean interpret bit value of memory referenced variable interpreted unsigned byte, regardless of signed integer representation used on system, i.e. if has bit value 0b10000000
should evaluate value 128, , 255 bit value 0b11111111
, accomplished reinterpret_cast.
now, two's complement representation happens same thing, since -128 represented 0b10000000
, -1 represented 0b11111111
, likewise in between. other computers (usually older architectures) may use different signed representation such sign-and-magnitude or ones' complement. in ones' complement 0b10000000
bitvalue not -128, -127, static cast unsigned char make 129, while reinterpret_cast make 128. additionally in ones' complement 0b11111111
bitvalue not -1, -0, (yes value exists in ones' complement,) , converted value of 0 static_cast, value of 255 reinterpret_cast. note in case of ones' complement unsigned value of 128 can not represented in signed char, since ranges -127 127, due -0 value.
i have vast majority of computers using two's complement making whole issue moot anywhere code ever run. ever see systems other two's complement in old architectures, think '60s timeframe.
the syntax boils down following:
signed char x = -100; unsigned char y; y = (unsigned char)x; // c static y = *(unsigned char*)(&x); // c reinterpret y = static_cast<unsigned char>(x); // c++ static y = reinterpret_cast<unsigned char&>(x); // c++ reinterpret
to in nice c++ way arrays:
jbyte memory_buffer[nr_pixels]; unsigned char* pixels = reinterpret_cast<unsigned char*>(memory_buffer);
or c way:
unsigned char* pixels = (unsigned char*)memory_buffer;
Comments
Post a Comment