#include #include #include #include #define readBits(start,size,data) ((*((uint64_t *) &data[(start) / 8]) >> ((start) & 7)) & ((1 << (size)) - 1)) uint64_t readData(const char* filename, unsigned int offset, unsigned int size) { uint64_t data = 0; int fd = open(filename, O_RDONLY); if(fd == -1) { return data; } if(lseek(fd, offset/8, SEEK_SET) == -1) { close(fd); return data; } ssize_t numBytes = read(fd, &data, sizeof(data)); if(numBytes != sizeof(data)) { close(fd); return data; } uint64_t* dataPtr = &data; uint64_t aux = readBits(offset % 8, size, dataPtr); data = aux; close(fd); return data; } int main(int argc, char** argv) { char c; const char* filename = NULL; unsigned int offset = 0; unsigned int size = 0; while ((c = getopt (argc, argv, "f:o:s:")) != -1) { switch(c) { case 'f': filename = optarg; break; case 'o': offset = atoi(optarg); break; case 's': size = atoi(optarg); break; case '?': return 1; } } if(!filename || !offset || !size) { fprintf(stderr, "Need to specify filename (-f), offset (-o) and size (-s)\n"); return 1; } uint64_t data = readData(filename, offset, size); printf("Read: 0x%016llX (%llu)\n", data, data); return 0; }