I have a set of 7 characters. I need to pull out the cell number in each ascii encoding from each character and convert the cell number to a binary form, so that I end up with a 56-bit binary array, how can this be done?

  • A string in C and so represents just an array of bytes. So the 7 byte string is the 56-bit binary array - Mike
  • But I need to work with these bits, besides, I can’t divide 7 bytes into two equal parts - user209927
  • What do you mean by “cell number”? - VladD
  • then take 3 bytes as is, and from the fourth take either the upper part b >> 4 , or the younger b & 0x0F only the unsigned char array, declare that no problems with the sign arise - Mike
  • If you are given an exhaustive answer, mark it as correct (a daw opposite the selected answer). - Nicolas Chabanovsky

2 answers 2

There are two approaches here.

first approach create structure and union

 struct bit_field { uint32_t bit00:1; uint32_t bit01:1; .... uint32_t bit56:1; uint32_t bit_rezerv:8; }; union union_field { struct bit_field; unsigned char symbol[7]; }__attribute__((packed)); 

write data to the symbol array and operate on bits in the structure

The second approach is to create a define set for operating on bits.

 #define BIT_00 0x01 #define SET_BIT_00(f) (f | BIT_00) #define UNSET_BIT_00(f) (f & (0xFF^BIT_00)) #define CHECK_BIT_00(f) (f & BIT_00) 

process each character separately

    Well, everything seems to be trivial.

     struct bit_array_builder { unsigned char* array; unsigned char* current_byte; size_t current_bit; }; void init_array(bit_array_builder* p_builder, size_t max_bits) { size_t max_bytes = (max_bits + (CHAR_BIT - 1)) / CHAR_BIT; p_builder->array = calloc(max_bytes, sizeof(unsigned char)); p_builder->current_byte = p_builder->array; p_builder->current_bit = 0; } void add_to_array(unsigned int value, size_t number_of_bits, bit_array_builder* p_builder) { while (number_of_bits > 0) { size_t remaining_bits = CHAR_BIT - p_builder->current_bit; size_t bits_in_chunk = remaining_bits > number_of_bits ? number_of_bits : remaining_bits; unsigned char partial_mask = (1 << bits_in_chunk) - 1; unsigned char partial_value = value & partial_mask; *(p_builder->current_byte) |= partial_value << p_builder->current_bit; p_builder->current_bit += bits_in_chunk; if (p_builder->current_bit == CHAR_BIT) { p_builder->current_bit = 0; p_builder->current_byte++; } number_of_bits -= bits_in_chunk; value >>= bits_in_chunk; } } 

    And you can test:

     int main() { bit_array_builder b; init_array(&b, 56); add_to_array(-1, 7, &b); add_to_array(0, 7, &b); add_to_array(-1, 7, &b); add_to_array(0, 7, &b); add_to_array(-1, 7, &b); add_to_array(0, 7, &b); add_to_array(-1, 7, &b); add_to_array(0, 7, &b); // на моей системе CHAR_BIT == 8 for (int i = 6; i >= 0; i--) { for (int bit = 7; bit >= 0; bit--) printf("%u", (b.array[i] >> bit) & 1); printf(" "); } } 

    Issues:

     00000001 11111100 00000111 11110000 00011111 11000000 01111111