Search code examples
c++mathbinarybit

Perform Operations like add, sub, mul, div, mod on 2 integers with their bytes


I have got the bytes of 2 integers (say 32 bit int) now is it possible to add them using the bytes?

I have like

char b1[4], b2[4];
int a= 2311;
int b= 233134;
memcpy(b1, &a, 4);
memcpy(b2, &b, 4);

My question is is there any algorithm to add, mul, sub the numbers from bytes and the number of bytes of number is not fixed it may be 32 bit, 64 bit, 128 bit.

Note i do not want any library or framewprk just c++


Solution

  • Your question is in its heart not about the implementation in C++, but about algorithms to do simple arithmetic.

    For all the operation you mention, remember how you did it in primary school. Apply that algorithms, replacing single decimal digits by bytes. The principle stays the same. It's all mathematics.

    You need to think how you detect carries and borrows between the bytes.

    Because you mentioned int as data type, you need to take the sign into account. It is easier if the values are unsigned.