问题描述
我阅读了Endianness并理解了蹲坐...
I read about Endianness and understood squat...
所以我写了这个
main()
{
int k = 0xA5B9BF9F;
BYTE *b = (BYTE*)&k; //value at *b is 9f
b++; //value at *b is BF
b++; //value at *b is B9
b++; //value at *b is A5
}
k
等于A5 B9 BF 9F
和(字节)指针"行走"的o/p为9F BF b9 A5
and (byte)pointer "walk" o/p was 9F BF b9 A5
所以我知道它的字节是向后存储的...好吧.
so I get it bytes are stored backwards...ok.
〜
所以现在我想到了如何将其存储在BIT级别...
so now I thought how is it stored at BIT level...
我的意思是将"9f"(1001 1111)存储为"f9"(1111 1001)吗?
I means is "9f"(1001 1111) stored as "f9"(1111 1001)?
所以我写了这个
int _tmain(int argc, _TCHAR* argv[])
{
int k = 0xA5B9BF9F;
void *ptr = &k;
bool temp= TRUE;
cout<<"ready or not here I come \n"<<endl;
for(int i=0;i<32;i++)
{
temp = *( (bool*)ptr + i );
if( temp )
cout<<"1 ";
if( !temp)
cout<<"0 ";
if(i==7||i==15||i==23)
cout<<" - ";
}
}
我得到一些随机输出
即使没有.像"32"一样,我什么都不懂.
even for nos. like "32" I dont get anything sensible.
为什么?
推荐答案
Endianness ,您通过实验发现的是指字节在对象中存储的顺序.
Endianness, as you discovered by your experiment refers to the order that bytes are stored in an object.
位没有不同的存储方式,它们始终是8位,并且始终是人类可读的"(高->低).
Bits do not get stored differently, they're always 8 bits, and always "human readable" (high->low).
现在我们已经讨论过,您不需要您的代码...关于您的代码:
Now that we've discussed that you don't need your code... About your code:
for(int i=0;i<32;i++)
{
temp = *( (bool*)ptr + i );
...
}
这没有按照您认为的去做.您要在0-32(一个单词的位数)之间进行迭代-很好.但是您的temp
分配都是错误的:)
This isn't doing what you think it's doing. You're iterating over 0-32, the number of bits in a word - good. But your temp
assignment is all wrong :)
请务必注意,bool*
的大小与int*
的大小相同,而与BigStruct*
的大小相同.同一台计算机上的所有指针大小都相同-32位计算机上为32位,而64位计算机上为64位.
It's important to note that a bool*
is the same size as an int*
is the same size as a BigStruct*
. All pointers on the same machine are the same size - 32bits on a 32bit machine, 64bits on a 64bit machine.
ptr + i
将i
字节添加到ptr
地址. i>3
时,您正在读一个全新单词...这可能会导致段错误.
ptr + i
is adding i
bytes to the ptr
address. When i>3
, you're reading a whole new word... this could possibly cause a segfault.
您要使用的是位掩码.这样的事情应该起作用:
What you want to use is bit-masks. Something like this should work:
for (int i = 0; i < 32; i++) {
unsigned int mask = 1 << i;
bool bit_is_one = static_cast<unsigned int>(ptr) & mask;
...
}
这篇关于如何根据“字节序"以位级别存储数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!