开发者

logical operations between chunks of memory?

开发者 https://www.devze.com 2023-04-08 09:16 出处:网络
I want to or two big chunks of memory... but it doesn\'t work Consider I have three char * bm, bm_old, and bm_res.

I want to or two big chunks of memory... but it doesn't work

Consider I have three char * bm, bm_old, and bm_res.

#define to_uint64(buffer,n) {(uint64_t)buffer[n] << 56 | (uint64_t)buffer[n+1] << 48 |        (uint64_t)buffer[n+2] << 40  | (uint64_t)buffer[n+3] << 32 | (uint64_t) buff开发者_如何学运维er[n+4] << 24 | (uint64_t)buffer[n+5] << 16 | (uint64_t)buffer[n+6] << 8  | (uint64_t)buffer[n+7];}

...

for (unsigned int i=0; i<bitmapsize(size)/8; i++){
      uint64_t or_res = (to_uint64(bm_old,i*8)) | (to_uint64(bm,i*8));
      memcpy(bm_res+i*sizeof(uint64_t), &or_res, sizeof(uint64_t));
}

bm_res is not correct!

Have any clue?

Thanks,

Amir.


Enclose the definition of to_uint64 in parentheses () instead of braces {} and get rid of the semicolon at the end. Using #define creates a macro whose text is inserted verbatim wherever it's used, not an actual function, so you were attempting to |-together two blocks rather than those blocks' "return values."


I think you need to advance your output pointer by the correct size:

memcpy(bm_res + i * sizeof(uint64_t), &or_res, sizeof(uint64_t));
                ^^^^^^^^^^^^^^^^^^^^

Since bm_res is a char-pointer, + 1 advances by just one byte.


You're incrementing bm_res by one for every eight-byte block you move. Further, you never increment bm or bm_old at all. So you're basically tiling the first byte of or_res over bm_res, which is probably not what you want.

More importantly, your code is byte-order sensitive - whether or_res is represented in memory as least-order-byte first or highest-order-byte first matters.

I would recommend you just do a byte-by-byte or first, and only try to optimize it if that is too slow. When you do optimize it, don't use your crazy to_uint64 macro there - it'll be slower than just going byte-by-byte. Instead, cast to uint64_t * directly. While this is, strictly speaking, undefined behavior, it works on every platform I've ever seen, and should be byteorder agnostic.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号