tags:

views:

130

answers:

3

Hello,

I have below code.

FILE *fp;
int a;
fp=fopen("dump.bin","wb");         
a = 0xffafbcdf;
fprintf(fp,"%x",a&0x3ffff);

I am trying to dump only 18 LSBits of variable a. But the value dumped in the file is 3bcdf.

My question - Is it not possible to dump/fwrite/fprintf desired number of bits which is not a multiple of 4(nibble) to a file?

Thank you

EDIT:

1.) When i checked the output of my file dump i realized, since i am opening file in binrary mode, i should not be using fprintf, but i should use fwrite.

2.) What i see in the output is DF BC 03 , it writes in multiples of 8 bits, so it writes 24 bits(3 bytes) but i was interested in only 18 bits. But then i realised thatno file write library will be able to write non-multiple of 8 bits to a file. it will always add leading zero bits to complete the byte and then dump it. "Least count unit" for a file data is a byte.

-AD.

A: 

0x3bcdf are the 18 LSBits of 0xffafbcdf, so it seems to be working as expected. What did you expect?

phihag
A: 

Files are written in bytes (8 bits), not nibbles (4bits).

Edit after your edit: fprintf will print text, thus you'll get 6 bytes, where-as if you used fwrite you will write an int (32 bit) to a file, but masking the value recorded.

Simeon Pilgrim
+1  A: 

As others have said, the character is the minimal sized entity you can write to a file. I'd just like to observe that there is nothing wrong with using fprintf() (or any other stream output function) on binary files.

anon
@Neil: If i used a fprintf() to write to file then it was dumping the ascii values for bytes 3 b c d f, i.e. file contained 32 62 63 64 66. Where as fwrite was dumping df bc 03.
goldenmean
Yes, they do different things, but they are both equally valid functions to use with binary files.
anon