开发者

c: pointers - how to increase every 2nd byte by X

开发者 https://www.devze.com 2023-02-01 04:42 出处:网络
I have a pointer that\'s开发者_StackOverflow holding 100 bytes of data. i would like to add 5 to every 2nd byte.

I have a pointer that's开发者_StackOverflow holding 100 bytes of data. i would like to add 5 to every 2nd byte.

example:

1 2 3 4 5 6

will become:

1 7 3 9 5 11

Now i know i can do a for loop, is there a quicker way? something like memset that will increase the value of every 2nd byte ?

thanks


A loop would be the best way. memset() is efficient for setting a contiguous block of memory. Wouldn't be much help for you here.


In which format do you have your bytes? As concatenated chars? Or are the bytes a subpart of e.g. a uint32?

In general, a loop is the best way for doing this - even if you would be able to apply a pattern-like mask with memset, you would still need to create it and that would take the same amount of CPU cycles.

If you would have 4 bytes per element (e.g. uint32), you could cut the cpu cycles in half by creating a pre-defined mask for adding. But attention: such a solution would not check for overflows (pseudocode):

uint32* ptr = new uint32[16]; // creates 64 bytes of data
(...) fill data
for (int k=0; k < 16; ++k)
{
   // Hardcored Add-Mask for Little Endian systems
   ptr[k] += 0x05000500; // dereference and add mask to content
}

Edit: Please note that this assumes a little endian system and is C++ Pseudocode.


If memset supported increasing the value of every nth byte, how do you think it would accomplish it?


You can in fact make it faster by using loop unrolling, but you'll need to know that your array is a fixed size. Then you would skip the loop overhead by just repeatedly assigning the value:

array[ 1 ] += 5;
array[ 3 ] += 5;
array[ 5 ] += 5;
...

By doing this you don't have the overhead incurred by jump and test instructions that would be present in a loop, but you pay for it in code bloat.

0

精彩评论

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