Skip to content

Instantly share code, notes, and snippets.

@liovch
Created May 25, 2013 00:31
Show Gist options
  • Save liovch/5647411 to your computer and use it in GitHub Desktop.
Save liovch/5647411 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#define IMAGE_WIDTH 7
#define DISPLAY_WIDTH 192
#define DISPLAY_HEIGHT 160
unsigned long int display[(DISPLAY_WIDTH * DISPLAY_HEIGHT) / 32];
int asciiHexToDec(char asciiHex)
{
if ((asciiHex >= '0') && (asciiHex <= '9')) return (asciiHex - '0');
if ((asciiHex >= 'A') && (asciiHex <= 'F')) return (10 + (asciiHex - 'A'));
return -1; // error
}
int zeroLastBits(int c, int bits)
{
return ((c >> bits) << bits);
}
int zeroLastBits2(int c, int bits)
{
int mask = (1 << bits);
mask = mask - 1;
mask = ~mask;
return (c & mask);
}
bool readFile()
{
FILE* file = fopen("image.hex", "r");
if (!file) return false;
int c;
unsigned long int result = 0;
int offsetSource = 28; // offset within result
int offsetDest = 0; // offset within display memory
int y = 0; // current line on display memory
int pixelsOnLine = 0; // total number of pixels written on the current line
while ((c = fgetc(file)) != EOF) {
c = asciiHexToDec(c);
if (c < 0) { // error
fclose(file);
return false;
}
if (pixelsOnLine + 4 <= IMAGE_WIDTH) {
result += (c << offsetSource);
offsetSource -= 4;
pixelsOnLine += 4;
if (offsetSource < 0) {
display[offsetDest] = result;
offsetDest++;
result = 0;
offsetSource = 28;
}
} else {
int pixelsNextLine = (pixelsOnLine + 4) - IMAGE_WIDTH;
int pixelsRemaining = 4 - pixelsNextLine;
int cCurrentLineValue = zeroLastBits2(c, pixelsNextLine);
int cNextLineValue = c - cCurrentLineValue;
// finish current line
result += (cCurrentLineValue << offsetSource);
display[offsetDest] = result;
y++;
offsetDest = y * (DISPLAY_WIDTH / 32);
result = 0;
offsetSource = 32 - pixelsNextLine;
// start next line
result += (cNextLineValue << offsetSource);
offsetSource -= 4;
pixelsOnLine = pixelsNextLine;
}
}
// flush the remaining data
display[offsetDest] = result;
fclose(file);
return true; // success
}
bool dumpDisplayMemory()
{
FILE* file = fopen("display.dat", "wb");
if (!file) return false;
for (int i = 0; i < (DISPLAY_WIDTH * DISPLAY_HEIGHT) / 32; i++) {
if (fwrite(&display[i], sizeof(display[0]), 1, file) != 1) { // error
fclose(file);
return false;
}
}
fclose(file);
return true; // success
}
int main(int argc, char* argv[])
{
if (!readFile()) return -1; // error
if (!dumpDisplayMemory()) return -1; // error
return 0; // success
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment