In: Computer Science
C language problem.
Suppose I open I file and read a integer 24. And I want to store them into a array byte [].
The answer should be byte[0] = 0x9F.
How can I do that?

#include <stdio.h>
int main(void) {
int x = 24;
// in C, there is no byte type, however char is of 1
// byte, hence we can treat it same way.
unsigned char byteArr[4];
byteArr[0] = x & 0xFF;
x = x >> 8; // shift to right by 8 bits.
byteArr[1] = x & 0xFF;
x = x >> 8; // shift to right by 8 bits.
byteArr[2] = x & 0xFF;
x = x >> 8; // shift to right by 8 bits.
byteArr[3] = x & 0xFF;
printf("0th byte(hex): %X\n", byteArr[0]);
printf("1st byte(hex): %X\n", byteArr[1]);
printf("2nd byte(hex): %X\n", byteArr[2]);
printf("3rd byte(hex): %X\n", byteArr[3]);
}
************************************************** 0x9F is equal to 16*9 + 15 = 159 in decimal.. So Your answer is incorrect. 24 is equal to 18 => 16 + 8 = 24 in decimal. Thanks for your question. We try our best to help you with detailed answers, But in any case, if you need any modification or have a query/issue with respect to above answer, Please ask that in the comment section. We will surely try to address your query ASAP and resolve the issue.
Please consider providing a thumbs up to this question if it helps you. by Doing that, You will help other students, who are facing similar issue.