Question

We generally say that the number 5 can be represented as a 3 bit binary number. But, if we convert 5 to its binary representation i.e. 101 and print it into a text file, it actually takes 3 bytes as it is read as a character array. How can I create a file (not necessarily a text file) such that the size of that file is 3 bits?

Était-ce utile?

La solution

You can logically represent 5 as three bits, but neither the filesystem nor the memory management system (for RAM) will let you address space in units smaller than one byte.

If you had eight of these numbers, you could pack them into 24 bits = 3 bytes and store those "efficiently" in memory or a file. Efficiently in quotes, because while you save some space, it becomes difficult to work with the packed data as you need to bit-shift things around a lot. CPU instructions, memory loads, array indexing etc all don't work with less-than-byte units.

The most practical way would be to just use a whole byte for your three bits and live with the overhead.

Autres conseils

I don't think you'll get a file system that will tell you the file is 3 bits. It will be at least a byte, plus storage for the file's extra information.

But you could simply open a file for writing and write 3 as binary.

FILE *ptr;

ptr = fopen("file", "wb");

fwrite('a', 1, 1, ptr);

You can use the following code and work based on this...the following code stores three numbers (5, 3 and 2) in a single byte. for storing the 3 numbers the file occupy only one byte. in general we can not store data in partial bytes in files.

#include<stdio.h>
struct bits
{
       unsigned char first:3,second:3,third:2;
};
main()
{
    struct bits b;
    FILE *f;
    b.first=5;
    b.second=3;
    b.third=2;

    printf("\ninitial data:%u %u %u",b.first,b.second,b.third);

    /*storing in file*/
    f=fopen("bitsfile","w");
    fwrite(&b,sizeof(b),1,f);
    fclose(f);

    /*reading back from file*/
    f=fopen("bitsfile","r");
    fread(&b,sizeof(b),1,f);
    fclose(f);

    printf("\ndata read from file:%u %u %u",b.first,b.second,b.third);
}

You generally can't since binary files have a minimal 'quantum' that is a byte ( 8 bit ). There is something interesting about storing symbols with not homogeneous bit length using Huffman Encoding. Just to explain before you read the complete article: your alphabet symbols stays each one on a binary tree leaf. There is a single path of 1 ( ie left ) 0 (ie right) starting from the root and landing to your symbol. If the tree is unbalanced ( and it would be) different symbols can be represented uniquely with different bit length. of course there is some effort because you have to read the file always at byte level, and then unpack and handle the bits with your algorithm implementation.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top