Olaf said:
How many bits we need to save the "number" 1 in a C text file? 00000001? 1
byte?
If it's a text file, then you're probably storing a number as a sequence
of ASCII characters (or possibly another encoding). The number 1 will be
output as a single character, which is usually a single byte, having the
binary value 110001 and the decimal value 49.
And the "number" 12? Is also a byte? 00001100?
No, it's two characters, '1' and '2'. The first character probably has
binary value 110001 (49) and the second probably has binary value 110010
(50). I say "probably" because on some systems the character encoding
used may not be compatible with ASCII.
The three characters '3', '0' and '0', in that order.
If you want to store numbers in a binary format, you can do that
instead. You then have to decide how many bytes you want to store for
each integer, and in what order to store the bytes.
For example:
fputc(val >> 24 & 255, file);
fputc(val >> 16 & 255, file);
fputc(val >> 8 & 255, file);
fputc(val >> 0 & 255, file);
The code above will output 4 bytes, each containing an 8-bit sequence of
the original value. The bytes are output in big-endian order. That means
that the most significant byte is output first, and the least
significant byte is output last. You can reverse the order of the 4
statements to make it output little-endian order instead.
If you want to store less bytes, just leave out the first statements. If
you want to store more bytes, add more statements and continue the
pattern, changing the shift value by 8 each time.
Simon.