Angelos Chalaris Angelos Chalaris - 4 months ago 14
C++ Question

Print matrix as black and white squares, similar to QR code

I am implementing a micro QR code generator in C++ and I want to print the final matrix that is generated as a set of black and white squares to look like a real QR code. My matrix is made up of integer values of

1
and
0
(there is a reason in my code for that, instead of using boolean values) and I want to print a black square for a value of
1
or a white square for a value of
0
.

My current code (see below or test it here) uses Unicode characters
\u2b1c
and
\u2b1b
to achieve a result similar to what I want but it is not square enough to be scanned by a QR code scanner.

Code

#include <iostream>
using namespace std;
int i,j;
int printPixels(int Board[11][11]){
for (i=0;i<11;i++){
for (j=0;j<11;j++) cout << ((Board[i][j] == 0) ? "\u2b1c" : "\u2b1b");
cout << endl;
}
return 0;
}
int main() {
int a[11][11]={
{1,1,1,1,1,1,1,0,1,0,1},{1,0,0,0,0,0,1,0,1,0,1},
{1,0,1,1,1,0,1,0,1,1,0},{1,0,1,1,1,0,1,0,0,0,0},
{1,0,1,1,1,0,1,0,1,1,1},{1,0,0,0,0,0,1,0,0,0,1},
{1,1,1,1,1,1,1,0,1,1,1},{0,0,0,0,0,0,0,0,0,1,1},
{1,1,0,0,1,1,1,0,0,1,0},{0,0,1,0,1,1,0,0,0,1,0},
{1,1,1,1,1,0,0,1,1,1,1}
};
printPixels(a);
}


Limitations


  • I can only use ASCII or Unicode characters to do this and not any drawing library or package (the reason for this is complicated, but this is my specification).

  • I need the implementation to be as platform-independent as possible and look good enough to scan if possible with a common QR code scanner.

  • I would like it to look good on something like Ideone, which has a white background instead of the usual black background of most terminals.


Answer

A possible alternative is to use space character for 0 and Unicode Character 'FULL BLOCK' (U+2588) █ to represent 1.

(Board[i][j] == 0) ? "  " : "\u2588\u2588";

You can see how it looks like here where I also used a pair of each character to take into account the font aspect ratio.