Is it possible to use bitwise operations on arrays (a long piece of memory)

Below are two arrays

int a[100]={1,1,...} int b[100]={2,5,...} 

Is there a way to manage them like this:

 c=a|b 

result c is

 {3,5,...} 

I want to work with memory as memcpy

I do not want to use loop

+5
source share
2 answers

Bitwise operations work by moving the operation elements into registers, and then perform the operation on the registers. This means that you are limited by the size of the registers for your operations, which are hardware dependent, but at best they are 64-bit (or 128 bits in some new hardware cases). This means that even with some tricks, you could perform bitwise operations at the same time. If speed is your concern, I would suggest using parallel to achieve your result. I should also mention that your example creates arrays on the stack, which limits the size of your array, which means that you will not be able to see noticeable changes in speed.

+3
source

You can declare your own array type in C ++ and overload the operator&() function:

 template<typename T, size_t N> class MyArray { template<typename X, size_t M> friend MyArray<X,M> operator&(const MyArray<X,M>& a, MyArray<X,M>& b) { MyArray<X,M> c; for(size_t i = 0; i < M; ++i) { c.array_[i] = a.array_[i] & b.array_[i]; } } std::array<T,N> array_; public: MyArray() { } MyArray(std::initializer_list l) array_(l) { } // ... }; 

And use it like

 MyArray<int,100> a { 1,1, /* ... */ }; MyArray<int,100> b { 2,5, /* ... */ }; MyArray<int,100> c = a&b; 

It is also possible to overload the operator&() function for std::array directly (perhaps the easiest way, as @Jarod suggested):

 template<typename T, size_t N> std::array<T,N> operator&(const std::array<T,N>& a, std::array<T,N>& b) { std::array<T,N> c; std::transform(std::begin(a), std::end(a), std::begin(b), std::begin(c), [](T i1, T i2) { return i1 & i2; }); return c; } 
+1
source

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


All Articles