Exchange lower byte (0-7) with higher (8-15) one

Now I know how this is done on one line, although I do not understand why my first draft does not work. What I'm trying to do is to save the bottom to another variable by moving the high byte to the right and adding two numbers through OR. However, it simply cuts the bottom half of the hexadecimal and returns the rest.

short int method(short int number) { short int a = 0; for (int x = 8; x < 16; x++){ if ((number & (1 << x)) == 1){ a = a | (1<<x); } } number = number >> 8; short int solution = number | a; return solution; 
+5
source share
2 answers

if ((number & (1 << x)) == 1)

This will return true if x is 0. Since 1 is in binary format 00000000 00000001 , and 1 << x will set everything except the x'th bit to 0.

You don't care if it's 1 or not, you just don't care if it's not equal to zero. Use

if (number & (1 << x))

+4
source

You do this one at a time; a better approach could do this with a single operation:

 uint16_t method(uint16_t number) { return (number << 8) | (number >> 8); } 

The above code explicitly specifies a 16-bit unsigned type, which avoids the problems associated with character expansion. To do this, you must include <stdint.h> (or <cstdint> in C ++).

+8
source

All Articles