martedì 26 marzo 2013

C++: valori binari -> bit

Programma che prende in input un file di testo in cui sono salvati dei valori scritti in forma binaria (0100010...) e che fornisce in uscita un file in cui sono scritti i bit singoli che rappresentano i valori binari.

#include <cstdio>
#include <iostream> 
#include <fstream>
#include <cstdlib>
#include <vector>

using namespace std;

int main(int argc, char *argv[]){
ifstream in(argv[1]);
ofstream out(argv[2]);


if(in.is_open()){printf("File %s trovato\n", argv[1]);}
else{printf("File %s NON trovato\n", argv[1]);}

if(out.is_open()){printf("File %s creato\n", argv[2]);}
else{printf("File %s NON creato\n", argv[2]);}

char c;
char buffer = 0;
int cont = 0;

while(in >> c){

if(c=='1' || c=='0'){
buffer = buffer*2 + (c-'0');
cont++;


if(cont==8){
out.write(&buffer, 1);
cont = 0;
}
}
}
while(cont>0){
buffer=buffer*2;
++cont;
if(cont==8){
out.write(&buffer, 1);
cont = 0;
}
}




in.close();
out.close();
}

Nessun commento:

Posta un commento