[英]C printf unsigned char array
I have an unsigned char array unsigned char* name = malloc(nameLength);
我有一个无符号字符数组,
unsigned char* name = malloc(nameLength);
- how can I print it with printf? -如何使用printf打印它?
%s
does not seem to work correctly, neither does %u
(seeing random icons). %s
似乎无法正常工作, %u
也不能正常工作(看到随机图标)。
Here's how I create the data I want to print: 这是我创建要打印的数据的方式:
__int32 nameLength;
ReadProcessMemory(hProcess, (LPCVOID)(classNamePtr + 0x0004), &nameLength, sizeof(__int32), 0); //Reads nameLength to be 13 in this case
unsigned char* name = malloc(nameLength+5); //Add 5 for good measure, it is null terminated
ReadProcessMemory(hProcess, (LPCVOID)(nameStrPtr), name, nameLength, 0);
name[nameLength] = 0; //null terminate
printf("%s", name); //Outputs single character strange characters, like an up icon
When one detects a non-printable char, output an escape sequence or hexadecimal value 当检测到不可打印的字符时,输出转义序列或十六进制值
#include <ctype.h>
#include <string.h>
#include <stdio.h>
int printf_ByteArray(const unsigned char *data, size_t len) {
size_t i;
int result = 0;
for (i = 0; i < len; i++) {
int y;
int ch = data[i];
static const char escapec[] = "\a\b\t\n\v\f\n\'\"\?\\";
char *p = strchr(escapec, ch);
if (p && ch) {
static const char escapev[] = "abtnvfn\'\"\?\\";
y = printf("\\%c", escapev[p - escapec]);
} else if (isprint(ch)) {
y = printf("%c", ch);
} else {
// If at end of array, assume _next_ potential character is a '0'.
int nch = i >= (len - 1) ? '0' : data[i + 1];
if (ch < 8 && (nch < '0' || nch > '7')) {
y = printf("\\%o", ch);
} else if (!isxdigit(nch)) {
y = printf("\\x%X", ch);
} else {
y = printf("\\o%03o", ch);
}
}
if (y == EOF)
return EOF;
result += y;
}
return result;
}
If data
contained one of each byte, sample follows: 如果
data
包含每个字节之一,则样本如下:
\\0...\\6\\a\\b\\t\\n\\v\\f\\xD\\xE\\xF\\x10...\\x1F !\\"#$%&\\'()*+,-./0123456789:;<=>\\?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\\x7F...\\xFE\\o377
The selection of escape sequences will vary with code goals. 转义序列的选择将随代码目标而变化。 The set above attempts to conform to something a C parser would accept.
上面的集合试图符合C解析器将接受的内容。
Note: With the last else
, always outputting a 3-digit octal sequence has scanning advantages, but folks are more accustomed to hexadecimal than octal. 注意:使用last
else
,始终输出3位数的八进制序列具有扫描优势,但是人们比八进制更习惯于十六进制。
Adjusted to conditionally print in hex depending on the following character. 调整为根据以下字符有条件地以十六进制打印。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.