在 C 中打印 char* 数组的十六进制值给出二进制输入的奇数值
这是一个奇怪的问题,一直困扰着我。
该程序是用 C89 编写的,它一次将文件读取到 char* 数组中 16 个字节(使用 fread 和 sizeof(char) 的大小)。该文件使用“rb”标志打开。然后将该数组传递给一个函数,该函数基本上采用 16 个十六进制值并将其粘贴到一个字符串中,每个值都用空格分隔。
这就是奇怪的地方。该函数为我输入的文本文件生成了一个很好的十六进制转储,一次 16 个字节。但如果我在一个小位图图像上尝试它,它就会搞砸——我最终会得到像 ffffff88 这样的字符串输出,而不仅仅是 88。
十六进制值使用 sprintf("%02x ", input[i ]);循环中。
为什么这对某些文件可以正常工作,但对其他文件却不能?
Here's an odd problem that's been stumping me for a bit.
The program is written in C89, and it reads a file into a char* array 16 bytes at a time (using fread and a size of sizeof(char)). The file is fopen'd with the "rb" flags. The array is then passed into a function that basically takes the 16 hex values and sticks it into a string, each value seperated by a space.
Here's where the weirdness comes in. The function produces a nice hex dump, 16 bytes at a time, for a text file input that I have. But it screws up if I try it on a small bitmap image -- I end up with output in the string like ffffff88 instead of just 88.
The hex values are placed into the output string using sprintf("%02x ", input[i]); in a loop.
Why would this work properly for some files but not others?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 C 中,char 被视为有符号值,除非您将其指定为无符号。似乎当您将参数传递给函数时,当参数恰好是字符时,它会被“填充”到常规整数的大小。如果您不告诉编译器这应该以无符号方式完成,则 128 会变成 0xFFFFFF80,依此类推。
因此,符号扩展发生在打印格式化程序查看该值之前。这意味着这
不会解决您的问题,因为 input[i] 的值将被符号扩展,因此从 128 到 255 的所有值都被视为 -127 到 -1 并变为 0xFFFFFF80 到 0xFFFFFF,然后进行转换,而
可以达到目的,但有点笨拙且难以阅读。最好首先将 input[] 的类型设置为 unsigned char。
In C the char is treated as a signed value, unless you specify it as unsigned. It seems that when you pass parameters to a function, that when the parameter happens to be a char, it's 'padded out' to the size of a regular integer. If you don't clue the compiler in that this should be done in an unsigned way, 128 becomes 0xFFFFFF80, and so on.
So, the sign extension happens before the print formatter ever gets to look at the value. What this means is that
won't solve your problem, as the value of input[i] will be sign extended, so all values from 128 to 255 are treated as -127 to -1 and become 0xFFFFFF80 to 0xFFFFFF, then cast, whereas
will do the trick, but is kind of ungainly and hard to read. Best to make the type of input[] be unsigned char in the first place.
您看到的是使用
unsigned char *
或转换为unsigned char
从char
到int
符号扩展的结果code> 在强制转换为 int 之前(隐式?)执行应该可以解决您的问题。What you see is the result of sign extension from the
char
toint
, usingunsigned char *
or casting tounsigned char
before the cast to int is (implicitly?) performed should fix your problem.