C / C ++: Bitwise operators in dynamically allocated memory

In C / C ++, is there an easy way to apply bitwise operators (in particular, left / right shifts) to dynamically allocated memory?

For example, let's say I did this:

unsigned char * bytes=new unsigned char[3];
bytes[0]=1;
bytes[1]=1;
bytes[2]=1;

I would like to do this:

bytes>>=2;

(then "bytes" will have the following meanings):

bytes[0]==0
bytes[1]==64
bytes[2]==64

Why should the values ​​be like this:

After allocation, the bytes are as follows:

[00000001][00000001][00000001]

But I am looking for processing bytes as one long string of bits, for example:

[000000010000000100000001]

A correct shift of two will cause the bits to look like this:

[000000000100000001000000]

Which, in the end, looks like this when they are separated back by 3 bytes (thus, 0, 64, 64):

[00000000][01000000][01000000]

? / ? : , ? . ( ) .

+3
5

, , , .

. - , .

, , . .

, "" , (.. ), - ...

void scroll_right (unsigned char* p_Array, int p_Size)
{
  unsigned char orig_l = 0;
  unsigned char orig_r;

  unsigned char* dest = p_Array;

  while (p_Size > 0)
  {
    p_Size--;

    orig_r  = *p_Array++;
    *dest++ = (orig_l << 7) + (orig_r >> 1);

    orig_l = orig_r;
  }
}

. (, 2, 4 8 ), .

, , .

" ", , orig_l . , , (orig_l < 7) . std::vector, .

EDIT , 2, 4 8 . , 2- char , .

x86 , . . ( 1), ( 3) ( 7), , . .

+2
  • /
  • , , , bitset .
  • boost::dynamic_bitset
  • ,

:

typedef unsigned char byte;

byte extract(byte value, int startbit, int bitcount)
{
   byte result;
   result = (byte)(value << (startbit - 1));
   result = (byte)(result >> (CHAR_BITS - bitcount));
   return result;
}

byte *right_shift(byte *bytes, size_t nbytes, size_t n) {
   byte rollover = 0;
   for (int i = 0; i < nbytes; ++i) {
     bytes[ i ] = (bytes[ i ] >> n) | (rollover < n);
     byte rollover = extract(bytes[ i ], 0, n);
   }
   return &bytes[ 0 ];
}
+2

:

unsigned int rollover = byte[0] & 0x3;
byte[0] >>= 2;

byte[1] = byte[1] >> 2 | (rollover << 6);

n . (0x3 6), .

+1

- :

#define number_of_bytes 3

template<size_t num_bytes>
union MyUnion
{
    char            bytes[num_bytes];
    __int64         ints[num_bytes / sizeof(__int64) + 1];
};

void main()
{
    MyUnion<number_of_bytes> mu;
    mu.bytes[0] = 1;
    mu.bytes[1] = 1;
    mu.bytes[2] = 1;
    mu.ints[0] >>= 2;
}

Just play with him. You will get an idea, I believe.

+1
source

Operator overloading is syntactic sugar. This is just a way to call a function and pass in your byte array, without having the appearance of calling a function.

So, I would start by writing this function

 unsigned char * ShiftBytes(unsigned char * bytes, size_t count_of_bytes, int shift);

Then, if you want to wrap this when overloading the statement, to make it easier to use, or because you simply prefer this syntax, you can also do this. Or you can just call the function.

0
source

Source: https://habr.com/ru/post/1735751/


All Articles