简体   繁体   中英

Combining two 8-bit integers to a 16-bit integer

IN C Programming, how do I combine (note: not add) two integers into one big integer? So if i have

int a = 8 int b = 6

in binary it would be int a = 1000 int b = 0110

so combined it would be = 01101000

You would use a combination of the << shift operator and the bitwise | operator. If you are trying to build an 8-bit value from two 4-bit inputs, then:

int a = 8;
int b = 6;

int result = (b << 4) | a;

If you are trying to build a 32-bit value from two 16-bit inputs, then you would write

result = (b << 16) | a;

Example:

#include <stdio.h>

int main( void )
{
  int a = 8;
  int b = 6;

  printf( "a = %08x, b = %08x\n", (unsigned int) a, (unsigned int) b );

  int result = (b << 4) | a;

  printf( "result = %08x\n", (unsigned int) result );

  result = (b << 8) | a;

  printf( "result = %08x\n", (unsigned int) result );

  result = (b << 16) | a;

  printf( "result = %08x\n", (unsigned int) result );

  return 0;
}

$ ./bits
a = 00000008, b = 00000006
result = 00000068
result = 00000608
result = 00060008

You can do it as follow using binary mask & 0x0F and bit translation << :

int a = 0x08
int b = 0x06
int c = (a & 0x0F) + ((b & 0x0F) << 4 )

I hope that it helped

Update 1:

As mentionned in the comment addition + or binary or | are both fine.

What is important to highlight in this answer is the mask & 0x0F , I strongly recommand to use this kind of mecanism to avoid any overflow.

you could use or operator.

int a = 8 ;
int b = 6 ;

int c = (a << 8) | b;

You can use the bit-shift operator << to move the bits into the correct position:

#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>

int main()
{
    uint8_t a = 8;
    uint8_t b = 6;

    uint16_t c = (b << 4) | a;

    printf( "The result is: 0x%" PRIX16 "\n", c );
}

This program will print the following:

The result is: 0x68

Note that this program uses fixed-width integer types , which are recommended in this situation, as you cannot rely on the size of an int or unsigned int to have a certain width.

However, there is no need for the result to be 16-bits, if you are only shifting one value by 4 bits, as you are doing in your example. In that case, an integer type with a width of 8-bits would have been sufficient. I am only using 16-bits for the result because you explicitly asked for it.

The macro PRIX16 will probably expand to "hX" or "X" on most platforms. But it is still recommended to use this macro when using fixed-width integer types, as you cannot rely on %hX or %X being the correct format specifier for uint16_t on all platforms.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM