简体   繁体   English

逐字节读取内存

[英]reading memory byte by byte

I've got a long[] which I'd like to read two bits at a time. 我有一个long [],我想一次读取两个位。 My data are the binary numbers 00,01,10, and 11 concatenated end to end, stuffed in a long, and then stuffed in an array. 我的数据是将二进制数00、01、10和11端对端连接在一起,填充为长整数,然后填充为数组。

I'll be reading a long stretch of this data at once, possibly starting halfway through, and it seems like it would make more sense to read straight from memory, two bytes at a time, rather than iterating through the long[] and pulling two bits at a time with a mask. 我将一次读取一长段数据,可能是从一半开始,看来直接从内存读取一次(一次两个字节)比遍历long []并拉取更有意义。每次带掩码两位。

I can't seem to figure out how I'd go about this, and I've never been great with directly accessing memory (since I was brought up on java). 我似乎无法弄清楚该如何去做,而且我从来都不擅长直接访问内存(因为我是在Java上长大的)。

I've tried instantiating an array 我试过实例化数组

unsigned long t[5];
t[0] = 4294967295;
t[1] = 0;
t[2] = 4294967294;
t[3] = 4294967296;
t[4] = 1;

and then printing *(&t) and *(&t+1) , but the plus one of course knows that it's the size of long and goes adds the appropriate value. 然后打印*(&t)*(&t+1) ,但是加号当然知道它是long的大小,所以会加上适当的值。

Use a pointer to a byte-sized data type. 使用指向字节大小的数据类型的指针。 Try this: 尝试这个:

unsigned char* p = (char *)t;

And use p pointer. 并使用p指针。

Well, you could always cast a pointer to char*, to get it byte by byte, if you also need to actually read it 2-bytes at a time, you'll need to use & and a proper bitmask (ie 0x3 to get the lowermost 2 bits). 好吧,您始终可以将指针转换为char *,以逐字节获取它,如果您还需要一次实际读取2个字节,则需要使用&和适当的位掩码(即0x3才能获取)最低2位)。 If you want, you can always just shift this mask with the << or >> operators to match further up or down in your current byte. 如果需要,您始终可以使用<<或>>运算符移动此掩码,以在当前字节中进一步向上或向下匹配。

Use an std::vector<bool> instead of a long[] for this. 为此,请使用std::vector<bool>而不是long[] Retrieving the i 'th 2-bit block can be done using 可以使用以下方法检索第i个2位块

(int(v[i*2]) << 1) | v[i*2+1]

Some simple arithmetic: 一些简单的算法:

for (unsigned int i = 0; i != 5; ++i)
{
     for (unsigned int k = 0; k != CHAR_BIT * sizeof(unsigned long int); k += 2)
     {
         std::printf("%02X ", n % 3);  // print last two bits
         n /= 4;                       // move down by two bits
     }
}

Instead of 5 you can of course say sizeof(t)/sizeof(t[0]) , if that's an option, or you can use iterators std::begin(t) / std::end(t) . 如果可以选择,当然可以说是sizeof(t)/sizeof(t[0])而不是5 ,或者可以使用迭代器std::begin(t) / std::end(t)

Cast the array to unsigned char * and print that. 将数组转换为unsigned char *并打印。 The first two bytes (endianness aside) would then be: 那么前两个字节(不包括字节序)将是:

((unsigned char *)t)[0]
((unsigned char *)t)[1]

...and so on ...等等

Edit: incidentally, t automatically decays to a pointer on its own, there's no need to do &t , you're just confusing yourself further. 编辑:顺便说一句, t本身会自动衰减为指针,无需执行&t ,您只是在进一步混淆自己。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM