[英]converting grayscale 8-bit to 32-bit
I have the following code我有以下代码
char c = 0xEE;
int color = 0xFF000000;
color += (int)c;
printf("%x\n", color);
I expected the result to be 0xFF0000EE;我预计结果是 0xFF0000EE; but instead the output was但相反的输出是
-> feffffee
What am I missing, i thought simply calculating我错过了什么,我以为只是计算
(int)(0xFF << 24 + c << 16 + c << 8 + c);
would give 0xFFEEEEEE but i get 0会给 0xFFEEEEEE 但我得到 0
EDIT:编辑:
the following code seems to work:以下代码似乎有效:
unsigned char c = 0xEE;
unsigned int color = 0xFF000000; /* full opacity */
color += (unsigned int)c;
color += (unsigned int)c << 8;
color += (unsigned int)c << 16;
printf("-> %x\n", color);
char
can be a signed type or an unsigned type. char
可以是有符号类型或无符号类型。 For you, it's apparently a signed type.对你来说,它显然是一种签名类型。 You end up assigning -18
, which is ffffffee when extended to 32 bits on a 2's complement machine.您最终分配了-18
,当在 2 的补码机上扩展到 32 位时,这是 ffffffee 。
Fixed:固定的:
#include <stdio.h>
int main(void) {
unsigned char c = 0xEE;
unsigned int color = 0xFF000000;
color |= c;
printf("%x\n", color);
return 0;
}
Portable:便携的:
#include <inttypes.h>
#include <stdint.h>
#include <stdio.h>
int main(void) {
unsigned char c = 0xEE;
uint32_t color = 0xFF000000;
color |= c;
printf("%" PRIx32 "\n", color);
return 0;
}
The following modifications will also result in 0xFF0000EE:以下修改也将导致 0xFF0000EE:
unsigned int c = 0x000000EE;
unsigned int color = 0xFF000000;
color = c | color;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.