0
#include <stdio.h>
#include <stdlib.h>

int main(){
    int n = 56789000;
    unsigned char bytes[4];

    bytes[0] = (n >> 24) & 0xFF;
    bytes[1] = (n >> 16) & 0xFF;
    bytes[2] = (n >> 8) & 0xFF;
    bytes[3] = n & 0xFF;

    int test = (bytes[3] << 24) | (bytes[2] << 16) | (bytes[1] << 8) | (bytes[0]);

    printf("%d\n",n);
    printf("%d\n", test);
}

Output is:

56789000
143155715

Hello,

I'm trying to store an integer into an unsigned char array and want to convert it back to an integer later. I found some code-snippets which lead me to the code above but the output is not as expected. Can you please help to fix the code above. I'm not very familiar with C and don't know what is wrong with the code.

Thank in advance

3
  • "he output is not as expected" What are you expecting? Commented Dec 18, 2014 at 10:59
  • 1
    I would expect that the same number will be printed twice. Commented Dec 18, 2014 at 11:00
  • 2
    I wouldn't since you're setting bytes[0] to the top 8 bits but then re-assembling with it as the lower 8 bits (and the same for the others). Try printing it in hex (%x) and all will become obvious. Commented Dec 18, 2014 at 11:02

1 Answer 1

1

This line is in the opposite order

int test = (bytes[3] << 24) | (bytes[2] << 16) | (bytes[1] << 8) | (bytes[0]);

so

int test = (bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | (bytes[3]);

should work.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot. Should have tried that. Have nice day.

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.