Reputation: 2828
So here is what i have/have to do. I have a .txt file that has a big picture of 132x72. What i need to do is put that into a c array of hex values.
I need to find a way to grab the first character of the top 8 lines and put them together horizontally so i can then convert them into hex. Then i need to do that 9 times down.
Example:
00000
00000
11111
01010
10101
10101
01010
10101
That i would need to turn into:
00101101
00110010
00101101
00110010
00101101
What is the best/simplest way to do this? I honestly do not know where to start.
Upvotes: 0
Views: 138
Reputation: 6823
This is an interesting format. In any event, read in a line and then add values appropriately to an array. This is what I mean:
Input Line 1: 01101
would correspond to some array: image[0][0] = 0, image[1][0] = 1 ...
This may be best done with std::vector
using the push_back()
method.
// If you know the image size already
unsigned char image[NUM_ROWS][NUM_COLS/8]; // 8 bits per byte
std::ifstream file("yourfile.txt", std::ifstream::in);
// Initialize the array to 0 with memset or similar
// Read the whole file
int rows = 0;
int cols = 0;
while(!file.eof) {
std::string line;
// Get line by line
std::getline(file, line);
// Parse each line (probably better in another function)
const char* str = line.c_str();
while(str[rows] != '\0') {
unsigned val = str[rows] - '0'; // Convert to int
unsigned shift = 8 - (rows % 8); // 8 bits per byte - this is tricky big-endian or little endian?
image[rows][cols/8] |= val << shift; // Convert to int val and pack it to proper position
rows++;
}
cols++;
rows = 0;
}
file.close();
The code is untested, but should give you a rough idea on how to read the data in properly. Now you have a properly formatted 2-dimensional array with your values (this is what the shifting was for). From here, you can take these values as int
values and convert them appropriately (a base 16 conversion is trivial from binary - i.e. each byte has two hexadecimal digits)
Upvotes: 0
Reputation: 8164
Assuming that the ones and zeros are characters (if it's something binary then you'll need to convert them first) in your .txt file: just read the file line by line into an array. You can then print the array with a stride, i. e. First print characters 0, 8, 16, 24 ... and then 1, 9, 17, ... and so on:
for (i = 0; i < ROWS; i++) {
for (j = 0; j < COLS; j++) {
printf("%c", chars[i + j * ROWS]);
}
printf("\n");
}
Something like that.
Upvotes: 2