I am trying to get some plain Ruby code ported to the C language for speed but I am not really being able to achieve that as C is not my primary language and I am struggling to understand what is causing it. Here is the code in Ruby for clarity of the purpose:
source_file = open("/tmp/image.jpg")
content = source_file.read
content_binary_string = content.unpack("b*")[0]
content_integer = content_binary_string.to_i(2)
I've been then playing around with several attempts in C to achieve the same results and somehow I am stuck on the binary comparison between the Ruby and C outputs. Here is the C code I've got so far:
// gcc -Wall -Wextra -std=c99 xxd.c
#include <stdio.h>
#include <string.h>
int main() {
char buffer[32];
FILE *image;
image = fopen("/tmp/image.jpg","rb");
while (!feof(image)) {
fread(buffer, sizeof(buffer), 1, image);
const size_t len = strlen(buffer);
for (size_t j = 0; j < len; j++ ) {
for (int i = 7; i >= 0; i--) {
printf(buffer[j] & (1 << i) ? "1" : "0");
}
}
}
return 0;
}
Please notice that the C code is not yet complete and that I am for now printing the binary value so I can compare the output with the current working code and I believe I am missing some basic concept that is abstracted by Ruby like byte size or something else that is not obvious to me yet. The output is quite different at this point.
After I get that step right, then the goal is to produce an integer based value from that.
Any clues towards understanding why that output isn't accurate is highly appreciated!