1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
#include <stdint.h>
void print_byte(uint8_t byte) {
for(int pos = 0; pos < 8; pos++) {
int bit_value = (byte >> (8 - 1 - pos)) & 1; // 001
char ch = '0' + bit_value;
fputc(ch, stdout);
}
}
void print_bytes(uint8_t* buf, size_t buf_len) {
for(int byte_idx = 0; byte_idx < buf_len; byte_idx++) {
print_byte(buf[byte_idx]);
fputc(byte_idx < buf_len - 1 ? ' ' : '\n', stdout);
}
}
void set_bit(uint8_t* a_buf_byte, int* a_pos_bit, int bit_value) {
*a_buf_byte |= bit_value << (8 - 1 - *a_pos_bit);
*a_pos_bit += 1;
}
void set_bits_from_string(uint8_t* buf, int* a_pos_byte, int* a_pos_bit, const char* s) {
for(const char* curr = s; *curr != '\0'; curr++) {
assert(*curr == '0' || *curr == '1' || *curr == ' ');
if(*curr != ' ') {
set_bit(&buf[*a_pos_byte], a_pos_bit, *curr - '0');
}
if(*a_pos_bit == 8) {
*a_pos_bit = 0;
*a_pos_byte += 1;
}
}
}
int main(int argc, char* argv[]) {
uint8_t buf[10] = {0}; // ⚠ Initialize all bytes to zero.
size_t buf_len = sizeof(buf) / sizeof(*buf); // ⚠ Only works with a true "array" (declared with [])
int pos_bytes = 0;
int pos_bit = 0; // 0 is most-significant (128's place), 7 is least significant (1's place)
// Write 0100 100 00 00 110 1011 1110 011 00 0101 100 00 00 1111 011 110 1011 1110 1010 011 110.
const char* s = "0100 100 00 00 110 1011 1110 011 00 0101 100 00 00 1111 011 110 1011 1110 1010 011 110";
set_bits_from_string(buf, &pos_bytes, &pos_bit, s);
print_bytes(buf, buf_len); // 01001000 ← this is correct
printf("01001000 00011010 11111001 10001011 00000011 11011110 10111110 10100111 10₀₀₀₀₀₀");
return EXIT_SUCCESS;
}
/* vim: set tabstop=4 shiftwidth=4 fileencoding=utf-8 noexpandtab: */
|
© Copyright 2020 Alexander J. Quinn This content is protected and may not be shared, uploaded, or distributed.