[ILUG] OT: Elementary C question
Michael Turley
samplecode at yahoo.com
Thu Jan 13 20:20:13 GMT 2000
I'm probably chancing my arm here but I've been trying
to finish a bit swapping program. The program is
supposed to reverse the bit order in every byte of a
binary file (I want it actually to reverse the bits in
a 2 byte type but that can wait for the moment).
The program seems only to process one byte and then
copy the rest of the file verbatim.
I would be indebted if some good, or even indifferent,
C programmer take a quick look at the code to see if
they can spot the obvious mistakes. Any thoughts (and
I mean any!) are more than welcome. Cheers and
apologies for the OT nature of the mail!
#include <stdio.h>
#define BSIZE 1024
void main() {
FILE *fin, *fout;
char buf [BSIZE];
int count;
unsigned char c2;
unsigned char d; /*d will be c
reversed*/
fin = fopen("little_end_file", "r");
fout = fopen("new_big_end_file", "w");
while ((count = fread(buf, 1, BSIZE, fin)) > 0) {
d=0;
c2=(char)*buf;
if (c2>=128) { /* If c2>=128 then
bit 7 is set */
d=d+1; /*set bit0 of d */
c2=c2-128; /* clear bit7 of c2
*/
};
if (c2>=64) { /* If c2>=64 then
bit 6 is set, etc. */
d=d+2;
c2=c2-64;
};
if (c2>=32) {
d=d+4;
c2=c2-32;
};
if (c2>=16) {
d=d+8;
c2=c2-16;
};
if (c2>=8) {
d=d+16;
c2=c2-8;
};
if (c2>=4) {
d=d+32;
c2=c2-4;
};
if (c2>=2) {
d=d+64;
c2=c2-2;
};
if (c2>=1) {
d=d+128;
c2=c2-1;
};
fwrite(&d, 1, count, fout);
}
fclose(fin);
fclose(fout);
}
====================
The other problem that I am having is that I cannot
get fread/fwrite to deal with bytesizes larger than 1
byte (e.g. fwrite (blah, sizeof(int), blah, blah);
outputs zero characters from its corresponding
fread(blah, sizeof(int), blah, blah);[1])
[1]while ((count = fread(buf, 2, BSIZE, fin)) > 0)
fwrite(buf, 2, count, fout);
=====
Mr. Michael Turley
Gracious winner, Generous lover, All round great guy.
http://www.tribune.ie/mike
__________________________________________________
Do You Yahoo!?
Talk to your friends online with Yahoo! Messenger.
http://im.yahoo.com
More information about the ILUG
mailing list