Initial DD

This commit is contained in:
Casey 2022-09-18 16:21:18 +03:00
commit 4c129f3bdd
Signed by: hkc
GPG Key ID: F0F6CFE11CDB0960
6 changed files with 112 additions and 0 deletions

3
.gitignore vendored Normal file
View File

@ -0,0 +1,3 @@
test_bitstream
main
*.o

13
Makefile Normal file
View File

@ -0,0 +1,13 @@
OBJECTS := bitstream.o
clean:
$(RM) *.o test_bitstream main
run_%: %
./$^
test_%: test_%.c $(OBJECTS)
$(CC) $^ -o $@
%.o: %.c
$(CC) $^ -c -o $@

44
bitstream.c Normal file
View File

@ -0,0 +1,44 @@
#include "./bitstream.h"
#include <stdio.h>
BitStream bitstream_load_from_file(FILE *fp) {
fseek(fp, SEEK_END, 0);
size_t length = ftell(fp);
fseek(fp, SEEK_SET, 0);
BitStream bs = bitstream_init_empty(length);
fread(bs.buffer, 1, length, fp);
return bs;
}
BitStream bitstream_init_empty(size_t size_in_bytes) {
return (BitStream){
.buffer = malloc(size_in_bytes),
.buffer_size = size_in_bytes,
.offset = 0
};
}
bool bitstream_end(BitStream bs) {
return (bs.offset >> 3) >= bs.buffer_size;
}
uint8_t bitstream_get(BitStream bs, off_t offset) {
return bs.buffer[offset >> 3] & (0x80 >> (offset & 7)) ? 1 : 0;
}
uint8_t bitstream_next(BitStream *bs) {
uint8_t val = bitstream_get(*bs, bs->offset);
bs->offset++;
return val;
}
void bitstream_set(BitStream bs, off_t offset, uint8_t value) {
bs.buffer[offset >> 3] &= ~(0x80 >> (offset & 7));
bs.buffer[offset >> 3] |= (value ? 1 : 0) * (0x80 >> (offset & 7));
}
void bitstream_unload(BitStream *bs) {
free(bs->buffer);
bs->buffer = 0;
}

25
bitstream.h Normal file
View File

@ -0,0 +1,25 @@
#ifndef _BITSTREAM_H_
#define _BITSTREAM_H_
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
typedef struct bit_stream {
uint8_t *buffer;
size_t buffer_size;
off_t offset;
} BitStream;
BitStream bitstream_load_from_file(FILE *fp);
BitStream bitstream_init_empty(size_t size_in_bytes);
uint8_t bitstream_get(BitStream bs, off_t offset);
uint8_t bitstream_next(BitStream *bs);
bool bitstream_end(BitStream bs);
void bitstream_set(BitStream bs, off_t offset, uint8_t value);
void bitstream_unload(BitStream *bs);
#endif

5
main.c Normal file
View File

@ -0,0 +1,5 @@
// x-run: make clean all run
#include "./bitstream.h"
int main(void) {
}

22
test_bitstream.c Normal file
View File

@ -0,0 +1,22 @@
// x-run: make clean test_bitstream run_test_bitstream
#include "./bitstream.h"
int main(void) {
BitStream bs = bitstream_init_empty(16 * 2);
bitstream_set(bs, 16 * 0 + 0, 1);
bitstream_set(bs, 16 * 2 + 2, 1);
bitstream_set(bs, 16 * 4 + 4, 1);
bitstream_set(bs, 16 * 8 + 8, 1);
bitstream_set(bs, 16 * 4 + 4, 0);
printf(" ");
for (int i = 0; i < 16; i++) printf("%2x", i);
printf("\n");
for (int i = 0; !bitstream_end(bs); i++) {
if (i % 16 == 0) printf("%2x", i >> 4);
printf("\033[%dm ", bitstream_next(&bs) \
? (i >> 4 & 1 ? 47 : 107) \
: (i >> 4 & 1 ? 40 : 100));
if (i % 16 == 15) printf("\033[0m\n");
}
bitstream_unload(&bs);
}