我遇到了一个有点奇怪的问题-我有一个字符数组,我想输出为十六进制。我不介意强制转换为int,但当我这样做时,会在一些数字的前面添加很多f。我让下面的代码为我输出:
for (int i = 0; i<(bmp.BytesPerRow*bmp.Height);i++) // once per color per pixel
{
if(i%3==0) // one line between each pixel
{
cout << "\n";
}
int tmp = (int) bmp.Raster[i];
cout << "\nbmp.Raster[" << i << "]": " << hex << tmp;
}我的输出如下所示:
bmp.Raster[0]: ffffffff
bmp.Raster[1]: ffffffff
bmp.Raster[2]: ffffffff
bmp.Raster[3]: 40
bmp.Raster[4]: 20
bmp.Raster[5]: ffffffe0
bmp.Raster[6]: 40
bmp.Raster[7]: ffffffe0
bmp.Raster[8]: 20
etc...坦率地说,我不明白。如果是这样我也能理解
ff
ff
ff
40
20
e0
etc...我可以理解,如果f被附加到所有东西上(我会认为它是造型过程的产物,只丢弃前6个输出),但只对某些输出?我还是不明白。
其他信息:
bmp.Raster来自Juan Soulie亲切提供的CRaster1类
IDE是Microsoft Visual C++ 2010Express,它自动包含"tchar.h",但我已经尝试注释掉了那个库,但奇怪的是仍然存在。
1个http://www.cplusplus.com/files/winbmp.zip
编辑:你们中的一些人正在提供解决方案的建议-我很感激-但我在这里最主要的问题是,是否有人知道发生了什么?
再次编辑:问题已由James Kanze解决。
循环已更改为:
for (int i = 0; i<(bmp.BytesPerRow*bmp.Height);i++) // once per color per pixel
{
if(i%3==0) // one line between each pixel
{
cout << "\n";
}
uint8_t tmp0 = (uint8_t)bmp.Raster[i];
uint16_t tmp1 = (uint16_t)tmp0;
cout << "\nbmp.Raster[" << i << "]": " << hex << tmp1;
}现在输出是正确的。
发布于 2011-04-07 18:20:32
问题是你机器上的普通字符是有签名的。(如果您不太关心可移植性,g++和VC++都可以选择将普通字符变为无签名字符。)您需要首先将char转换为unsigned char,然后将unsigned char转换为int。或者,如果您可以更改要输出的数据结构,则将其更改为使用无符号字符;这似乎更适合于位图之类的东西。
发布于 2011-04-07 17:19:26
不是这样的:
int tmp = (int) bmp.Raster[i];但这一点:
int tmp = (unsigned int) bmp.Raster[i]; // OR
unsigned int tmp = bmp.Raster[i];也许行得通。
当您将字节值转换为(带符号的)整数时,字节的符号位(高位)将被传播以填充整数的高位部分。因此,(比方说) 0x80的一个字节变成了类似于0xffffff80的整数。无符号算术产生您想要的行为。
发布于 2011-04-07 17:33:33
使用这一行:
unsigned char tmp = bmp.Raster[i];而不是:
int tmp = (int) bmp.Raster[i];也许能行得通。
https://stackoverflow.com/questions/5578682
复制相似问题