c - Storing a two-bit binary in char -
so i'm working on program takes file of characters , turns these file of characters of binary numbers. have able read these characters (the binary characters) , turn them denoted characters.
so encoding , decoding file.
so have file 4 characters: '@', '/n', ':', ' '. (last 1 space)
so reason want have bunch of ascii pictures want store in smaller files.
i have been told can use unsigned char, set 0, read file characters described above, , use bitwise operators assign values read unsigned char , each 4 characters read (because each character 8 bites , these can turned 2 bites each , stored in 1 character, hence 4 characters in 1 char) append (add) each number char.
any appreciated!
the code have this:
#include <stdio.h> #include <stdlib.h> #include <string.h> file *inputfile; file *outputfile; int encodebinary[4] = {0x00, 0x01, 0x02, 0x03}; char encodechars[4] = {':', '@', '\n', ' '}; //reads file , creates encoded file void encode(const char * infile, const char * outfile) { inputfile = fopen(infile, "r"); outputfile = fopen(outfile, "w"); char linebuffer[bufsiz]; int size = 0; char temp = 0; if(inputfile == null) { perror("error while opening file.\n"); exit(exit_failure); } while(fgets(linebuffer, sizeof(linebuffer), inputfile)) { for(int = 0; linebuffer[i] != 0; i++) { //adds 4 different characters char before adding character file if(size < 4) { if(linebuffer[i] == encodechars[0]) { } else if(linebuffer[i] == encodechars[1]) { } else if(linebuffer[i] == encodechars[2]) { } else if(linebuffer[i] == encodechars[3]) { } size++; } else { size = 0; temp = 0; } } } fclose(inputfile); fclose(outputfile); } would appreciate if come examples how add bits read in temp char. have no idea how can add numbers char moved in such way , added in such way represent old numbers , new. i'm thinking can bitshift number 3 times left, 01 becomes 0100.
instead of using bitfields, use << , >> operators , bitwise & , | manipulate bits directly,
encode,
unsigned char accum; if(size>0) accum = encodechars[0] << 6 if(size>1) accum |= encodechars[0] << 4 if(size>2) accum |= encodechars[0] << 2 if(size>3) accum |= encodechars[0] if(linebuffer[i] accum decode,
char array[4]; if(size>0) array[0] = decodechars[ (accum >> 6) &0x3 ]; if(size>1) array[1] = decodechars[ (accum >> 4) &0x3 ]; if(size>2) array[2] = decodechars[ (accum >> 2) &0x3 ]; if(size>3) array[3] = decodechars[ (accum) &0x3 ]; and read big-endian vs. little-endian understand element storage order.
Comments
Post a Comment