3

Can you explain about how to convert the last 3 bytes of data from unsigned integer to a character array?

Example:

unsigned int unint = some value;
unsigned char array[3];
2
  • 6
    What do you mean by the last three bytes? Commented Jan 24, 2012 at 15:51
  • I guess he means the least significant 3 bytes but I might be wrong. Commented Jan 24, 2012 at 15:53

4 Answers 4

6

It's more difficult if you have to convert it to an array, but if you just want to access the individual bytes, then you can do

char* bytes = (char*)&unint;

If you really do want to make an array (and therefore make a copy of the last 3 bytes, not leave them in place) you do

unsigned char bytes[3]; // or char, but unsigned char is better

bytes[0] = unint >> 16 & 0xFF;
bytes[1] = unint >> 8  & 0xFF;
bytes[2] = unint       & 0xFF;
Sign up to request clarification or add additional context in comments.

Comments

5

You can do using it the bitwise right shift operator:

array[0] = unint;
array[1] = unint >> 8;
array[2] = unint >> 16;

The least signifcant byte of uint is stored in the first element of the array.

1 Comment

@Nick In a char array of length 3?
0

Depending on your needs, you may prefer an union:

typedef union {
    unsigned int  unint;
    unsigned char array[3];  
} byteAndInt;

or bit-shift operations:

for(int i=0; i<3; i++)
    array[i] = (unint>>8*i) & 0xFF;

The former is not endian-safe.

5 Comments

Isn't it UB to write to one member of a union and read the other without writing to it first?
@Seth UB by the standard but well-defined by all compilers I've ever encountered.
An union specifies that the same memory zone can be interpreted several ways. This is the very purpose of it to write one field and read another one. Of course, executing the same code on a big-endian machine and on a little-endian one gives different results. but this is a portability issue, not UB.
@Seth Not anymore. In C11, well, in n1570, fn 95 in 6.5.2.3 says "the appropriate part of the object representation of the value is reinterpreted as an object representation in the new type as described in 6.2.6 (a process sometimes called ‘‘type punning’’). This might be a trap representation".
@DanielFischer oh, I didn't know about C11, I thought the last one was C99. Thanks.
0

If by last three, you mean lsb+1, lsb+2 and msb (in other words every byte other than the lsb), then you can use this.

unsigned int unint = some value;
unsigned char * array = ( (unsigned char*)&some_value ) + 1;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.