C语言 C 中从字节到 ASCII 的转换
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2565782/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Conversion from Byte to ASCII in C
提问by name_masked
Can anyone suggest means of converting a byte array to ASCII in C? Or converting byte array to hex and then to ASCII?
任何人都可以建议在 C 中将字节数组转换为 ASCII 的方法吗?或者将字节数组转换为十六进制然后再转换为 ASCII?
[04/02][Edited]: To rephrase it, I wish to convert bytes to hex and store the converted hex values in a data structure. How should go about it?
[04/02][编辑]:重新表述一下,我希望将字节转换为十六进制并将转换后的十六进制值存储在数据结构中。应该怎么办?
Regards, darkie
问候,小黑
采纳答案by quinmars
First of all you should take some more care on the formulation of your questions. It is hard to say what you really want to hear. I think you have some binary blob and want it in a human readable form, e.g. to dump it on the screen for debugging. (I know I'm probably misinterpreting you here).
首先,您应该更加注意问题的制定。很难说出你真正想听到的。我认为您有一些二进制 blob 并希望它以人类可读的形式出现,例如将其转储到屏幕上以进行调试。(我知道我可能在这里误解了你)。
You can use snprintf(buf, sizeof(buf), "%.2x", byte_array[i])for example to convert a single byte in to the hexadecimal ASCII representation. Here is a function to dump a whole memory region on the screen:
snprintf(buf, sizeof(buf), "%.2x", byte_array[i])例如,您可以使用将单个字节转换为十六进制 ASCII 表示。这是一个在屏幕上转储整个内存区域的函数:
void
hexdump(const void *data, int size)
{
const unsigned char *byte = data;
while (size > 0)
{
size--;
printf("%.2x ", *byte);
byte++;
}
}
回答by Eli Bendersky
Well, if you interpret an integer as a charin C, you'll get that ASCII character, as long as it's in range.
好吧,如果你将一个整数解释为charC 中的 a,你就会得到那个 ASCII 字符,只要它在范围内。
int i = 97;
char c = i;
printf("The character of %d is %c\n", i, c);
Prints:
印刷:
The character of 97 is a
Note that no error checking is done - I assume 0 <= i < 128(ASCII range).
请注意,没有进行错误检查 - 我假设0 <= i < 128(ASCII 范围)。
Otherwise, an array of byte values can be directly interpreted as an ASCII string:
否则,可以将字节值数组直接解释为 ASCII 字符串:
char bytes[] = {97, 98, 99, 100, 101, 0};
printf("The string: %s\n", bytes);
Prints:
印刷:
The string: abcde
Note the last byte: 0, it's required to terminate the string properly. You can use bytesas any other C string, copy from it, append it to other strings, traverse it, print it, etc.
注意最后一个字节:0,需要正确终止字符串。您可以bytes像任何其他 C 字符串一样使用、从中复制、将其附加到其他字符串、遍历它、打印它等。
回答by zellio
Char.s and Int.s are stored in binary in C. And can generally be used in place of each other when working in the ASCII range.
Char.s 和 Int.s 在 C 中以二进制形式存储。在 ASCII 范围内工作时,通常可以相互代替使用。
int i = 0x61;
char x = i;
fprintf( stdout, "%c", x );
that should print 'a' to the screen.
应该在屏幕上打印“a”。

