I know that in order to reach the bytes of a number we should do:
unsigned int number=value;
char* bytes = (char*)&number;
...but I don't really understand why.
Why do we need to use char *? Why are we casting here?
Thank you :)
I know that in order to reach the bytes of a number we should do:
unsigned int number=value;
char* bytes = (char*)&number;
...but I don't really understand why.
Why do we need to use char *? Why are we casting here?
Thank you :)
Not entirely sure what your problem is here.
Why do we need to use char *?
A char is a byte (read: 8 binary numbers 0 or 1) that can represent a decimal value from 0-255 or -128 - +127 in signed form. It is by default signed.
an int
is bigger then a byte, hence the need to cast it to get a byte.
Not sure without the context why you'd want to, but you can use that to determine endianness. Related SO Question
If you want to get to the bytes of an int, you need a pointer that points at something the size of a byte. A char
is defined as the size of a byte, so a pointer to a char
lets you get the individual bytes of an int.
int a[10]
int *p_int= &a[0];
p_int++;
The p_int++
increments the variable by the size of an int and so will point to a[1]
. It increments with 4 bytes.
char *p_char= (char *)&a[0];
p_char++;
The p_char++
increments the variable by the size of a char and so will point to the second byte of the integer a[0]
.