bins c code example
Example 1: c program from decimal to binary
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#define D 10
int main()
{
int i, n, k, vet[D];
printf("FROM DECIMALS TO BINARIES\nEnter decimal: ");
scanf("%d", &n);
k = 0;
while (n != 0)
{
if ((n % 2) == 1)
vet[k] = 1;
else
vet[k] = 0;
n /= 2;
k++;
}
printf("Transformed into binary: ");
for(i = k - 1; i >= 0; i --)
printf("%d", vet[i]);
printf("\n\n");
system("pause");
}
Example 2: file binari c
#include<stdlib.h>
#include<stdio.h>
int main() {
FILE *fd;
int res;
int x;
int max;
int posmax;
fd=fopen("test.dat", "r+");
if( fd==NULL ) {
perror("Errore in apertura del file");
exit(1);
}
max=0;
while(1) {
res=fread(&x, sizeof(int), 1, fd);
if( res!=1 )
break;
if( x>max ) {
max=x;
posmax=ftell(fd)-sizeof(int);
}
}
fseek(fd, posmax, SEEK_SET);
x=0;
fwrite(&x, sizeof(int), 1, fd);
fclose(fd);
return 0;
}