[英]char array not properly initialized
I have am array of chars that I'm using for bytecode. 我有用于字节码的字符数组。 Printing them out one by one should yield the same hex values that you see here: 逐个打印它们应该产生相同的十六进制值,你在这里看到:
char toWrite[] = {'\x50','\x48','\xB8','\x00','\x00','\x00','\x00','\x00','\x00','\x00','\x00','\xFF','\xE0' };
When I try to print these values out in a loop, however, they are mangled. 但是,当我尝试在循环中打印这些值时,它们会被破坏。 What I see instead is: 我所看到的是:
50 48 ffffffb8 00 00 00 00 00 00 00 ffffffff ffffffe0
Why are these chars printing wrong? 为什么这些字符打印错误? I am iterating in a foreach loop, and every single element is passed to 我在foreach循环中迭代,并传递每个元素
cout << hex << (int)currentChar << endl;
For most systems, char
is 8 bits wide and is a signed integer type. 对于大多数系统, char
是8位宽并且是有符号整数类型。 Storing \\xB8
will make its most significant bit 1, which will make it negative. 存储\\xB8
将使其最重要的位1,这将使其为负。 And casting it to int
will also result in a negative value, resulting in 0xffffffb8
if int
is 32 bits wide. 并将其转换为int
也将导致负值,如果int
为32位宽,则导致0xffffffb8
。
You should use unsigned char
: 你应该使用unsigned char
:
unsigned char toWrite[] = {/*...*/};
Also, static_cast
is more preferable than C-style cast: 另外, static_cast
比C风格的static_cast
更优选:
cout << hex << static_cast<int>(currentChar) << endl;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.