如何将 long long ASCII 十六进制值转换为字符串?
我有一个 long long
保存 ASCII 十六进制值,并希望将其转换为字符串。我有这样的代码:
char myBuffer[8];
long long myLongLong = 0x7177657274797569;
sprintf(myBuffer,"%c%c%c%c%c%c%c%c",myLongLong);
int x;
cout << myBuffer;
cin >> x;
return 0;
十六进制代码应该是 "qwertui"
,但它总是给出其他值。
我尝试使用 %c
、%s
、%X
但它没有给我所需的输出,最接近的是 %c
但它只打印出一个字符。
I have a long long
holding ASCII hex values and want to convert it to a string. I have this code:
char myBuffer[8];
long long myLongLong = 0x7177657274797569;
sprintf(myBuffer,"%c%c%c%c%c%c%c%c",myLongLong);
int x;
cout << myBuffer;
cin >> x;
return 0;
The hex code should be "qwertyui"
, but it always gives other value.
I tried with %c
, %s
, %X
but it doesn't give me the output I need, the closest was %c
but it prints out only one char.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
该代码在很多方面都是错误的,我不知道从哪里开始...
myBuffer
太小,无法容纳 8chars
+ NUL 终止符,即。应该是myBuffer[9]
。sprintf
需要 8 个参数,而您只传递 1 个。其他必需的参数将是堆栈上的任何参数。myLongLong
不是char
最接近您想要的几乎工作示例,与您的示例类似,类似于:
这将在我的小设备上输出
“iuytrewq”
- 字节序机器。正如我提到的,这没有考虑字节序。如果机器是小端字节序,那么您可以反向读取/打印字节。我真的不明白你为什么要这样做......
That code is wrong in so many ways I don't know where to start...
myBuffer
is too small to hold the 8chars
+ the NUL terminator, ie. should bemyBuffer[9]
.sprintf
is expecting 8 arguments, you're only passing 1. The other required arguments will be whatever's on the stack.myLongLong
is not achar
std::string
s as opposed to C-style strings andstringstream
s as an alternative tosprintf
?The closest almost working example of what you want, as similar to your example, is something like:
Which will output
"iuytrewq"
on my little-endian machine. As I mentioned, that doesn't take into account the endianness. If the machine is little-endian then you could read/print the bytes in reverse.I really don't understand why you're trying to do this though...
你可以尝试
,但我不明白你真正想要做什么。那么字节序呢?
You could try
But I don't understand what you want really to do. What about endianness ?
使用字符串流
Use a string stream
您想将 long-long 的每个字节打印为 ascii 字符吗?
然后,您需要循环一次 long long 提取一个字节,查看位移位和掩码。
提示通常更容易(如果您知道长度)从最后一个字节开始工作并右移
,或者 - 您可以将 long-long memcpy 到 char 数组中 - 除了任何字节排序问题
You want to print each byte of the long-long as an ascii char?
Then you need to loop over the long long extracting one byte at a time, look at bit shifts and masking.
Hint it's generally easier (if you know the length) to work from the last byte and shift right
or - you could just memcpy the long-long into the char array - except for any byte ordering issues
尝试以下代码。
Try the following code.