Reputation: 13
I have an array that holds 28 ints which are all 1's and 0's. However, I need to print this information as 4 characters so how do I get each 7 bytes of data to become one bit in order to print.
Not sure this makes sense so I will illustrate what I need to:
Right now my array (in order) is this: 0101101111011101011000100010 But I need to somehow take those first 7 numbers (0101101) and print that out as Z and do that with the next 7, the next 7...
Thanks for your help!
Upvotes: 0
Views: 1818
Reputation: 964
I think this might be something along the lines you are looking for.
int to_int(int *bits) {
int power = 2;
int digit = 1;
int value = 0;
int i=0;
for(i=0; i <= 6; i++) {
if(bits[i] == 1) {
value += digit;
}
digit *= power;
}
return value;
}
int main() {
int myArray[28] = {0, 1, 0, 1, 1, 0, 1,
1, 1, 1, 0, 1, 1, 1,
0, 1, 0, 1, 1, 0, 0,
0, 1, 0, 0 ,0, 1, 0};
char theChars[5];
theChars[0] = to_char(&myArray[0]);
theChars[1] = to_char(&myArray[7]);
theChars[2] = to_char(&myArray[14]);
theChars[3] = to_char(&myArray[21]);
theChars[4] = '\0';
printf("%s\n",&theChars[0]);
}
Also, I don't think your expected output is correct.
Upvotes: 1
Reputation: 1533
Assuming your input array is called inputBits[]
Try something like this:
const int input_bit_count = 28;
char output[input_bit_count / 7];
int outIdx = 0;
// step through the bit stream converting bits to 7-bit characters
for( int inIdx = 0; inIdx < input_bit_count; ){
// shift over and add the next bit to this character
output[outIdx] <<= 1;
if( inputBits[inIdx] != 0 ){
output[outIdx] |= 1;
}
inIdx++;
if( inIdx % 7 == 0)
// after each 7 bits, increment to next output character
outIdx++;
}
// done processing, now print it out
for( int chIdx = 0; chIdx < input_bit_count / 7; chIdx++ ){
printf( "%c", output[chIdx] );
}
Upvotes: 0
Reputation: 379
Well, there is always the stupid way: Cycle through each 7 blocks.
int bytes=7;
for(int i=0; i++;i<4){
double ASCII = 0;
for(int j=0; i++;j<bytes){
ASCII+=Math.pow(2, bytes-j-1)*array[i*bytes + j]
}
char c = (char) ASCII // you'll have some trouble with types here
}
Upvotes: 0