как изменить код так, чтобы вместо While было for , и при переводе с 10 в 2 систему использовалось не вычитание а деление?
#include <stdio.h>
#include <math.h>
#include <stdbool.h>
#include <string.h>
void encode_char(const char character, bool bits[8]){
int number[] = {128 , 64 , 32 , 16 ,8 ,4 ,2 ,1};
float x = 0;
float y = character;
int i = 0;
while(i != 8){
x = y;
y = y - number[i];`перевод из 10 в 2 с помощью вычитания`
if(y < 0){
bits[i] = false;
y = x;
}
else if(y >= 0){
bits[i] = true;
}
i = i + 1;
}
}
int main() {
bool bits1[8];
encode_char('A', bits1);
for(int i = 0; i < 8; i++){
printf("%d", bits1[i]);
}
printf("\n");
return 0;
}
Ответы (1 шт):
Автор решения: wololo
→ Ссылка
#include <limits.h>
#include <stdbool.h>
void encode_char(unsigned char character, bool bits[CHAR_BIT]) {
for (int i = CHAR_BIT - 1; i >= 0; --i) {
bits[i] = character % 2 != 0;
character /= 2;
}
}