[英]Converting integer to unsigned char* (int 221 to “\xdd”)
I have a function which takes unsigned char*
as input. 我有一个函数,将
unsigned char*
作为输入。
Say for example that I have: 例如说我有:
unsigned char* data = (unsigned char*) "\xdd";
int a = 221;
How can I convert my integer a
to unsigned char*
such that data
and my converted a
is indistinguishable? 如何将我的整数
a
转换为unsigned char*
,以使data
和转换后的a
无法区分? I have tried playing around with sprintf but without any luck, I'm not sure how to handle the "\\x" part. 我尝试过使用sprintf,但是没有运气,我不确定如何处理“ \\ x”部分。
Since 221
is not guaranteed to be a valid value for a char
type, the closest thing you can do is: 由于不能保证
221
是char
类型的有效值,因此您可以做的最接近的事情是:
int a = 221;
unsigned char buffer[10];
sprintf((char*)buffer, "%c", a);
Here's an example program and its output: 这是一个示例程序及其输出:
#include <stdio.h>
int main()
{
unsigned char* data = (unsigned char*) "\xdd";
int a = 221;
unsigned char buffer[10];
sprintf((char*)buffer, "%c", a);
printf("%d\n", buffer[0] == data[0]);
printf("%d\n", buffer[0]);
printf("%d\n", data[0]);
}
Output: 输出:
1
221
221
Update 更新
Perhaps I misunderstood your question. 也许我误解了你的问题。 You can also use:
您还可以使用:
int a = 221;
unsigned char buffer[10] = {0};
buffer[0] = a;
As stated the question does not make sense and is not possible - you don't actually want to convert to const char *
, which is a pointer type. 如前所述,这个问题是没有意义的,也是不可能的-您实际上并不希望转换为指针类型的
const char *
。 Instead you want to convert into an array of char
s and then take the address of that array by using its name. 相反,您想要转换为
char
数组,然后使用其名称获取该数组的地址。
int x = 221;
char buf[5];
snprintf(buf, sizeof buf, "\\x%.2x", x);
/* now pass buf to whatever function you want, e.g.: */
puts(buf);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.