Last active
January 8, 2018 13:48
-
-
Save parastuffs/542636096417361cd72992a44be2f28c to your computer and use it in GitHub Desktop.
ELECH305 - Examen janvier 2018
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> /* memset */ | |
#include <math.h> /* log */ | |
/* ELECH305 - Janvier 2018 | |
------------------------------------------------------------------------------------------------- | |
Complétez le code suivant pour que le nombre entier entré par l'utilisateur soit écrit en base 8. | |
int main() | |
{ | |
int in; | |
scanf("%i", &in); | |
// ... | |
return EXIT_SUCCESS; | |
} | |
------------------------------------------------------------------------------------------------- | |
Les points essentiels sont les suivants: | |
- Choix du masque | |
- Décalage dans le bon sens en fonction de l'ordre de remplissage du tableau | |
- Application correcte du masque | |
Les points bonus sont les suivants : | |
- Considérer le cas où in == 0 | |
- Consiférer le cas où in < 0 | |
- Adapter la taille du tableau à la taille de in | |
- Écrire une fonction | |
- ??? | |
Gist https://gist.github.com/parastuffs/542636096417361cd72992a44be2f28c | |
*/ | |
int main() | |
{ | |
int in = 45; | |
int i; | |
char isNeg = 0; | |
scanf("%i", &in); | |
if(in == 0) { | |
printf("0\n"); | |
return EXIT_SUCCESS; | |
} | |
else { | |
if(in < 0) { | |
isNeg = 1; | |
in = -in; | |
} | |
/* Ce calcul de tabSize est facultatif. | |
Il est acceptable de fixer sa taille à la valeur maximale | |
admissible par un int, soit (log_8(2**31 - 1) + 1 = 11. */ | |
int tabSize = log(in)/log(8) + 1; | |
/* On fait d'office +1. Si le résultat n'est pas entier, | |
le int arrondit vers le bas et il faut faire +1. | |
Si le résultat est entier, ça veut dire qu'il pourrait nous manquer | |
chiffre. Par exemple, log_8(64) = 2, mais sa représentation en octal | |
est 100, c'est-à-dire trois chiffres.*/ | |
char * tab = malloc( tabSize * sizeof(char)); | |
memset(tab, 0, tabSize); | |
char mask = 0x7; | |
for(i = 0; i<tabSize; i++) { | |
tab[tabSize -1 -i] = (in >> (i*3)) & mask; | |
} | |
for(i = 0; i<tabSize; i++) | |
printf("%i", (isNeg && i == 0)? -tab[i] : tab[i]); | |
printf("\n"); | |
} | |
return EXIT_SUCCESS; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment