0

Consider the following code :

unsigned char byte = 0x01;

In C/C++ the hexadecimal will be considered as an int, and therefore will be expanded to more then one byte. Because there is more then one byte, if the system uses little or big endian has effect. My question is to what this will be expanded?

If the system has int that contains 4 bytes, to which of the following it will be expanded :

0x00000001 OR 0x01000000

And does the endianness effect to which of them it will be expanded?

csavvy
  • 761
  • 4
  • 13
  • 5
    It doesn't matter in this instance. `byte` will end up with `0x01` any way. – pmg Oct 24 '20 at 19:53
  • Are you essentially asking what `int x = 0x01` results in for the value of `x`? Or what the underlying value of bytes in memory will be for the bytes that make up `x`? – TheUndeadFish Oct 24 '20 at 19:56
  • My question was for the byte, is there a chance that on some system it will be expanded and end up with a value of 0, instead of 1. Now that I understand it can't happen, what will be the value of x in this cases? – rrrrTTTrrrr Oct 24 '20 at 20:00
  • 1
    "If the system has 'int' that contains 4 bytes". The 32-bit representation of `0x01` *in memory* is `01 00 00 00` in a little-endian system, and `00 00 00 01` in a bigendian system. Nothing is lost. If you are storing in one byte it is `01` regardless. – Weather Vane Oct 24 '20 at 20:00

2 Answers2

1

The endianness does't matter. The endianness only relates to how the value is stored in memory. But the value represented by what's stored in memory will be 0x01, no matter how it is stored.

Take for example the value 0x01020304. It can be stored in memory as either 01 02 03 04 or 04 03 02 01. But in both cases it's still the value 0x01020304 (or 16 909 060).

AVH
  • 11,349
  • 4
  • 34
  • 43
1

It is completely architecture specific. The compiler produces the output according to your computer's endianness. Assuming that your microprocessor is big-endian, the compiler will produce;

char x = 0x01; --> 01,
int x = 0x01;  --> 00 00 00 01

On the other hand, if you use a cross compiler that targets little-endian or you compile the code on a little-endian machine, it will produce;

char x = 0x01; --> 01
int x = 0x01;  --> 01 00 00 00

Summarily, there is no standard or default endianness for the output, the output will be specific to the architecture which the compiler targets to.