Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c

I now know how it's done in one line, altough I fail to realise why my first draft doesn't work aswell. What I'm trying to do is saving the lower part into a different variable, shifting the higher byte to the right and adding the two numbers via OR. However, it just cuts the lower 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;
like image 584
Jan Avatar asked Apr 02 '15 15:04

Jan


People also ask

How do you do a byte swap?

Given a byte, swap the two nibbles in it. For example 100 is be represented as 01100100 in a byte (or 8 bits). The two nibbles are (0110) and (0100). If we swap the two nibbles, we get 01000110 which is 70 in decimal.

What is lower byte and higher byte?

The bits of a word are numbered from 0 through 15; bit 0 is the least significant bit. The byte containing bit 0 of the word is called the low byte; the byte containing bit 15 is called the high byte.

How do you put on nibble upper?

The trick to setting a nibble is to clear the desired four bits first, and then to OR in the new value. Use 0xF0 mask to clear out the lower nibble; for the upper nibble the mask is 0x0F .

What is byte in C?

A byte is typically 8 bits. C character data type requires one byte of storage. A file is a sequence of bytes. A size of the file is the number of bytes within the file. Although all files are a sequence of bytes,m files can be regarded as text files or binary files.


1 Answers

You are doing it one bit at a time; a better approach would do it with a single operation:

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

The code above specifies 16-bit unsigned type explicitly, thus avoiding issues related to sign extension. You need to include <stdint.h> (or <cstdint> in C++) in order for this to compile.

like image 123
Sergey Kalinichenko Avatar answered Sep 18 '22 04:09

Sergey Kalinichenko