Home > OS >  Combining two 8-bit integers to a 16-bit integer
Combining two 8-bit integers to a 16-bit integer

Time:09-29

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

CodePudding user response:

You can do it as follow:

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

I hope that it helped

CodePudding user response:

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 = x, b = x\n", (unsigned int) a, (unsigned int) b );

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

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

  result = (b << 8) | a;

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

  result = (b << 16) | a;

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

  return 0;
}

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

CodePudding user response:

you could use or operator.

int a = 8 ;
int b = 6 ;

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

CodePudding user response:

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.

  • Related