In: Computer Science
(In C language)
Given a two-dimensional char array, how do I encode it into a one dimensional integer array? For example:
char arr [8][8] = {{1,1,1,1,1,1,1,1}, {1,0,0,0,1,0,0,1}, {1,0,1,0,1,1,0,1}, {1,0,1,0,0,0,0,1}, {1,0,1,1,1,1,0,1}, {1,0,0,0,0,0,0,1}, {1,0,1,0,1,0,1,1}, {1,1,1,1,1,1,1,1}} into int arr2 [8]
I know this problem requires bit-shifting but I am unsure how. It also needs to be as efficient as possible.
Thanks!
If you have any queries please comment in the comments section I will surely help you out and if you found this solution to be helpful kindly upvote.
Solution :
#include <stdio.h>
// main function
int main()
{
// define a 2d character array
char arr [8][8] = {{1,1,1,1,1,1,1,1}, {1,0,0,0,1,0,0,1},
{1,0,1,0,1,1,0,1}, {1,0,1,0,0,0,0,1}, {1,0,1,1,1,1,0,1},
{1,0,0,0,0,0,0,1}, {1,0,1,0,1,0,1,1}, {1,1,1,1,1,1,1,1}};
// initialize a 1d integer array
int arr2[8];
// iterate the 2d charater array
for(int i=0;i<8;i++)
{
// declare val = 0
int val=0;
for(int j=0;j<8;j++)
{
// use bit shifting and add to val to get the number
val = val + (arr[i][j])*(1<<(8-j-1));
}
// insert the integer val to the integer array
arr2[i]=val;
}
// print the integer array
for(int i=0;i<8;i++)
{
printf("%d ",arr2[i]);
}
return 0;
}