Skip to content

Instantly share code, notes, and snippets.

@warmonkey
Last active March 5, 2023 09:50
Show Gist options
  • Save warmonkey/49dd574fda39f88b5eed5edc92707cf2 to your computer and use it in GitHub Desktop.
Save warmonkey/49dd574fda39f88b5eed5edc92707cf2 to your computer and use it in GitHub Desktop.
Xilinx .bit file header parser
class HeaderParser {
private:
uint8_t state;
//0=header len, 1=header data,
//2=key, 3=length, 4=value,
//5=bitstream len, 6=bitstream
uint32_t len;
uint8_t n;
uint8_t key;
protected:
virtual void parseKey(uint8_t k, char c) {
printf("key 0x%x: %c\n", k, c);
}
public:
bool done() {
return (state == 6);
}
void reset() {
state = 0;
n = 2;
}
size_t bitstream_len() {
if(state == 6) return len;
else return 0;
}
HeaderParser() {
reset();
}
void operator()(char x) {
switch(state) {
case 0: { //record header len
len = (len << 8) | x;
n--;
if(n == 0) {
n = len & 0x0000ffff;
if(n == 0x0001) state = 2; //go key-length-value mode
else state = 1; //go bitstream len
}
} break;
case 1: //consume header data
n--;
if(n == 0) {
n = 2;
state = 0;
}
break;
case 2: //parse key
key = x;
if(key == 0x65) {
n = 4;
state = 5;
} else {
n = 2;
state = 3;
}
break;
case 3: { //record value len
len = (len << 8) | x;
n--;
if(n == 0) {
n = len & 0x0000ffff;
state = 4;
}
} break;
case 4: { //consume value
parseKey(key, x);
n--;
if(n == 0) state = 2;
} break;
case 5: { //record bitstream len
len = (len << 8) | x;
n--;
if(n == 0) state = 6; //bitstream len acquired
}
case 6:
default:;
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment