Last active
August 29, 2015 14:05
-
-
Save kyontan/5c71753d7d6b5f60bd3b to your computer and use it in GitHub Desktop.
Slice bit string
This file contains hidden or 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<stdbool.h> | |
void print_bit_string(unsigned char n) { | |
for(int i=7; 0<=i; i--) { | |
printf("%d", (n >> i) & 1); | |
} | |
} | |
unsigned char slice_bit_string(unsigned char data[], int data_len, char slice_unit, int idx) { | |
int data_len_bits = data_len * 8; | |
unsigned char sliced, mask; | |
int shift, data_idx; | |
mask = (1 << slice_unit) - 1; | |
data_idx = (idx * slice_unit) / 8; | |
shift = (idx * slice_unit) % 8; | |
sliced = (data[data_idx] & (mask << shift)) >> shift; | |
// mask したいデータが配列の要素を跨っている時 | |
if (8 < shift + slice_unit && idx * slice_unit <= data_len_bits) { | |
// temp_mask: A に対応するマスク | |
// ex) data: 0101 0101 | |
// mask: 0011 1000 | |
// temp_mask: 0011 // mask >> (8-shift) | |
// A B | |
int temp_mask = mask >> (8-shift); | |
sliced |= (data[data_idx+1] & temp_mask) << (8-shift); | |
} | |
return sliced; | |
} | |
int main() { | |
unsigned char data[] = {248, 137}; | |
int data_len = sizeof(data) / sizeof(unsigned char); | |
for (int i = 0; i < data_len; i++) { | |
printf("data[%d] = ", i); | |
print_bit_string(data[i]); | |
printf("\n"); | |
} | |
int slice_unit = 3; // 分割単位 | |
int loop_cnt = data_len * 8 / slice_unit; | |
if (data_len * 8 % slice_unit) | |
loop_cnt += 1; | |
unsigned char sliced; | |
for (int i = 0; i < loop_cnt; i++) { | |
sliced = slice_bit_string(data, data_len, 3, i); | |
printf("sliced[%d] = %d = ", i, sliced); | |
print_bit_string(sliced); | |
printf("\n"); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment