3
votes

I want to convert an unsigned int and break it into 2 chars. For example: If the integer is 1, its binary representation would be 0000 0001. I want the 0000 part in one char variable and the 0001 part in another binary variable. How do I achieve this in C?

6
What platform are you on? On most PCs we use today usually int has a size of 4, and char 1. If you are sure that it has a size of 2 it's unlikely that you aren't familiar with bitwise tricks.phoeagon
It appears that you have eight bits total (one byte) and you are breaking it into two 4-bit values, however the title of your post indicates you have two bytes.Vaughn Cato

6 Answers

6
votes

If you insist that you have a sizeof(int)==2 then:

  unsigned int x = (unsigned int)2; //or any other value it happens to be
  unsigned char high = (unsigned char)(x>>8);
  unsigned char low  = x & 0xff;

If you have eight bits total (one byte) and you are breaking it into two 4-bit values:

  unsigned char x=2;// or whatever
  unsigned char high = (x>>4);
  unsigned char low = x & 0xf;
3
votes

Shift and mask off the part of the number you want. Unsigned ints are probably four bytes, and if you wanted all four bytes, you'd just shift by 16 and 24 for the higher order bytes.

unsigned char low  =  myuint       & 0xff;
unsigned char high = (myuint >> 8) & 0xff;
2
votes

This is assuming 16 bit ints check with sizeof!! On my platform ints are 32bit so I will use a short in this code example. Mine wins the award for most disgusting in terms of pulling apart the pointer - but it also is the clearest for me to understand.

unsigned short number = 1;

unsigned char a;
a = *((unsigned char*)(&number)); // Grab char from first byte of the pointer to the int

unsigned char b;
b = *((unsigned char*)(&number) + 1); // Offset one byte from the pointer and grab second char
2
votes

One method that works is as follows:

typedef union 
{
  unsigned char c[sizeof(int)];
  int           i;
} intchar__t;

intchar__t x;
x.i = 2;

Now x.c[] (an array) will reference the integer as a series of characters, although you will have byte endian issues. Those can be addressed with appropriate #define values for the platform you are programming on. This is similar to the answer that Justin Meiners provided, but a bit cleaner.

0
votes
unsigned short s = 0xFFEE;
unsigned char b1 = (s >> 8)&0xFF;
unsigned char b2 = (((s << 8)>> 8) & 0xFF);

Simplest I could think of.

0
votes
int i = 1  // 2 Byte integer value 0x0001
unsigned char byteLow = (i & 0x00FF); 
unsinged char byteHigh = ((i & 0xFF00) >> 8); 

value in byteLow is 0x01 and value in byteHigh is 0x00