Chen Li
Chen Li

Reputation: 151

Dividing by a factor of 2 and byte operations C++

I know the best way to divide a number by 2 is to move one bit to the left. What do I do if I am dividing by a multiple of 2 (for example 8), do I move over by 3 bits, here are my questions:

  1. How can I do such operations in C++, bit movement?
  2. How can I access higher byte of an int and lower byte of an int, if I wanted to swap their values?

I know these operations can be done at the assembly level because we are dealing with registers, I just don't know if we have access to such things in C++.

Upvotes: 0

Views: 1242

Answers (1)

Damon
Damon

Reputation: 70206

Accessing the higher/lower bytes of an integer, and swapping them can be done in at least two ways. Either a combination of >> and |, or with a union.

For example something like:

short swapped = (original<<8)|(original>>8);

will give you the two bytes of a 2-byte integer swapped. If you have a larger integer (e.g. 4 bytes), some more masking and shifting will be required, if all bytes are needed in some particularly shuffled order.

Optimizing divisions by multiples of 2 with right shift (>>) is a no-optimization. You should write readable code that gives a clear idea of what is intended. The compiler will trivially perform such micro-optimizations.

Upvotes: 3

Related Questions