Question:
a. Why does the program deliver a 8-bit hex number (0xFFFFFFFF) when the input is 0xFF and when the sizeof() delivers char as 4-bit ?
This code is
wrong when you want to display the size of a char (in bits):
printf("Size of char: %d-bits\n", sizeof(char)*4);
Sure it will report that a
char variable consists out of 4 bits, but there's something wrong with your code, for example: how did you come up with this magic 4? For what does it stand? Second: the
sizeof operator will always (under all circumstances, on all platforms return 1 if you invoke:
sizeof(char) ), so this multiplied by 4 will
always give 4 as the result.
The correct way to get the correct size in bits per byte (a char is always 1 byte) is by using the
CHAR_BIT macro as defined in the
limits.h header (you have to include this file if you want to use the
CHAR_BIT macro, you can do this by adding this directive to the top of your program:
#include <limits.h> ).
The correct way of getting the size (in bits) of a variable of type
char and or
integer in C:
char:
printf("Size of a variable of type char (in bits): %lu", CHAR_BIT);
integer:
printf("Size of a variable of type integer (in bits): %lu", CHAR_BIT*sizeof(int));
What exactly does CHAR_BIT represent?
The
CHAR_BIT macro represents the number of bits in a byte (a variable of type
char does always have the size of one byte, as defined per standard, but this isn't the case for variables of other types, they depend on your C-implementation).
So multiplying the value of
CHAR_BIT by the
sizeof of a certain variable type (int, double, float...) will give you the number of bytes that type consists of.
Note that
sizeof(type) returns the size (
in bytes) of a variable type.
Also notice that I used the
%lu format specifier in the format string passed to the
printf() function, this is because the
sizeof operator returns a value of an unsigned integral datatype (as defined per standard), to produce portable code I added the
%lu format specifier (which will ensure a cast to an
unsigned long, the biggest unsigned integral type) to make sure that the size will always be displayed correctly on the screen.