C++ 如何获取C+中字符的整数值+;?
我想将存储在32位无符号整数中的值,放入四个字符中,然后将每个字符的整数值存储在一个字符串中 我认为第一部分是这样的:C++ 如何获取C+中字符的整数值+;?,c++,bit-manipulation,endianness,C++,Bit Manipulation,Endianness,我想将存储在32位无符号整数中的值,放入四个字符中,然后将每个字符的整数值存储在一个字符串中 我认为第一部分是这样的: char a = orig << 8; char b = orig << 8; char c = orig << 8; char d = orig << 8; unsigned char byte1=orig&0xff; unsigned char byte2=(orig>>8)&0xff; unsi
char a = orig << 8;
char b = orig << 8;
char c = orig << 8;
char d = orig << 8;
unsigned char byte1=orig&0xff;
unsigned char byte2=(orig>>8)&0xff;
unsigned char byte3=(orig>>16)&0xff;
unsigned char byte4=(orig>>24)&0xff;
char myString[256];
sprintf(myString,"%x %x %x %x",byte1,byte2,byte3,byte4);
chara=orig不完全是:
char a = orig & 0xff;
orig >>= 8;
char b = orig & 0xff;
orig >>= 8;
char c = orig & 0xff;
orig >>= 8;
char d = orig & 0xff;
不太清楚“将这些值中的每个值的整数值存储到字符串中”是什么意思。要将0x10111213
转换为“16 17 18 19”
,还是什么?对于十六进制:
sprintf(buffer, "%lX", orig);
对于十进制:
sprintf(buffer, "%ld", orig);
使用snprintf
以避免缓冲区溢出。使用联合
(根据要求,这里是示例程序。)
#包括
#包括
使用名称空间std;
我的联盟
{
结构字符
{
无符号字符d,c,b,a;
}mychars;
无符号整数myint;
};
内部主(空)
{
美联;
u、 myint=0x41424344;
cout假设“orig”是一个包含值的32位变量
我想你想做这样的事情:
char a = orig << 8;
char b = orig << 8;
char c = orig << 8;
char d = orig << 8;
unsigned char byte1=orig&0xff;
unsigned char byte2=(orig>>8)&0xff;
unsigned char byte3=(orig>>16)&0xff;
unsigned char byte4=(orig>>24)&0xff;
char myString[256];
sprintf(myString,"%x %x %x %x",byte1,byte2,byte3,byte4);
顺便说一句,我不确定这是否总是endian正确。(编辑:事实上,它是endian正确的,因为位移位操作不应该受到endianness的影响)
希望这有帮助。如果您确实想先提取单个字节:
unsigned char a = orig & 0xff;
unsigned char b = (orig >> 8) & 0xff;
unsigned char c = (orig >> 16) & 0xff;
unsigned char d = (orig >> 24) & 0xff;
或:
或者使用无符号长字符和四个字符的并集:
union charSplitter {
struct {
unsigned char a, b, c, d;
} charValues;
unsigned int intValue;
};
charSplitter splitter;
splitter.intValue = orig;
// splitter.charValues.a will give you first byte etc.
更新:正如friol所指出的,解决方案2和3并不是不确定尾数的;哪些字节a
、b
、c
和d
取决于CPU架构。十进制、八进制、十六进制或二进制?您的问题和标题似乎都是奇数,而且都不够精确。为了更清楚,您能否重述一遍?在使用unicode的国际环境中,这似乎非常脆弱,其中一个字符实际上是多字节的…一旦我有了这些字符,我想打印它们的整数value@Clayton,用完全相同的词语以稍微不同的顺序重复这个问题,这不是我所说的“澄清”“或者使用流运算符。这是一个C++问题。这样做的问题是,在不同的二进制数的系统上会得到不同的结果。这将给你在大的和小的Endiad机器上的相同的答案。你可能想要使用%%D%D%D”或“%X%X%X”。解决方案2和3不是endian正确的(它们在不同的机器上会给出不同的结果)。