【发布时间】:2015-03-30 18:29:27
【问题描述】:
我搜索了很多网站,但似乎找不到任何相关内容。
我希望能够获取每个默认数据类型的单个字节,例如 short、unsigned short、int、unsigned int、float 和 double,并将每个单独的字节信息(二进制部分)存储到每个索引中无符号字符数组。如何实现?
例如:
int main() {
short sVal = 1;
unsigned short usVal = 2;
int iVal = 3;
unsigned int uiVal = 4;
float fVal = 5.0f;
double dVal = 6.0;
const unsigned int uiLengthOfShort = sizeof(short);
const unsigned int uiLengthOfUShort = sizeof(unsigned short);
const unsigned int uiLengthOfInt = sizeof(int);
const unsigned int uiLengthOfUInt = sizeof(unsigned int);
const unsigned int uiLengthOfFloat = sizeof(float);
const unsigned int uiLengthOfDouble = sizeof(double);
unsigned char ucShort[uiLengthOfShort];
unsigned char ucUShort[uiLengthOfUShort];
unsigned char ucInt[uiLengthOfInt];
unsigned char ucUInt[uiLengthOfUInt];
unsigned char ucFloat[uiLengthOfFloat];
unsigned char ucDouble[uiLengthOfDouble];
// Above I declared a variable val for each data type to work with
// Next I created a const unsigned int of each type's size.
// Then I created unsigned char[] using each data types size respectively
// Now I would like to take each individual byte of the above val's
// and store them into the indexed location of each unsigned char array.
// For Example: - I'll not use int here since the int is
// machine and OS dependent.
// I will use a data type that is common across almost all machines.
// Here I will use the short as my example
// We know that a short is 2-bytes or has 16 bits encoded
// I would like to take the 1st byte of this short:
// (the first 8 bit sequence) and to store it into the first index of my unsigned char[].
// Then I would like to take the 2nd byte of this short:
// (the second 8 bit sequence) and store it into the second index of my unsigned char[].
// How would this be achieved for any of the data types?
// A Short in memory is 2 bytes here is a bit representation of an
// arbitrary short in memory { 0101 1101, 0011 1010 }
// I would like ucShort[0] = sVal's { 0101 1101 } &
// ucShort[1] = sVal's { 0011 1010 }
ucShort[0] = sVal's First Byte info. (8 Bit sequence)
ucShort[1] = sVal's Second Byte info. (8 Bit sequence)
// ... and so on for each data type.
return 0;
}
【问题讨论】:
-
你怎么知道没有短是 32 位的系统?
-
了解工会。不确定“每种默认数据类型的单个字节”是什么意思。
-
我说在大多数机器上短是 2 个字节。这并不意味着全部,但更可能的是短是 2 字节,然后使用可能是 16 位(2 字节过时)、32 位(x86 上常见 4 字节)和 64 位(64 位机器上常见 8 字节)的整数。
-
@Raw N - 是的,我已经阅读了联合,但这是否也会保留字节顺序,还是必须在不同平台之间进行转换?另外,我想制作一个可以接受任何数据类型变量并执行此操作并返回 unsigned char* 的函数
-
对齐和顺序取决于系统。
标签: c++ arrays bit-manipulation byte