-2
#include <stdio.h>
int main()
{
    int x = 255;
    char hex[4] = {0};
    hex[0] = 0x02;
    hex[1] = 0x20;
    hex[2] = 0xef;
    hex[3] = x;
    for(int i = 0; i < 4; i++)
        printf("%X ", hex[i]);
}

This outputs " 2 20 FFFFFFEF FFFFFFFF". What should be changed so that it would output "02 20 EF FF"?

Matiz 12
  • 1
  • 1

1 Answers1

0

The question is the data overflowed. char is -128 ~ 127, when 0xef = 239. So you can use type int or short or just unsigned char , like that:

#include <stdio.h>
int main()
{
    int x = 255;
    unsigned char hex[4] = {0};
    hex[0] = 0x02;
    hex[1] = 0x20;
    hex[2] = 0xef;
    hex[3] = x;
    for(int i = 0; i < 4; i++)
        printf("%02X ", hex[i]);
}
Claim Yang
  • 309
  • 1
  • 9