Problem with writing a hexadecimal string
        Posted  
        
            by quilby
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by quilby
        
        
        
        Published on 2010-04-08T20:36:31Z
        Indexed on 
            2010/04/08
            20:53 UTC
        
        
        Read the original article
        Hit count: 400
        
Here is my code
/*
gcc -c -Wall -g main.c
gcc -g -lm -o main main.o
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
void stringToHex(const char* string, char* hex) {
 int i = 0;
 for(i = 0; i < strlen(string)/2; i++) {
  printf("s%x", string[2*i]); //for debugging
  sprintf(&hex[i], "%x", string[2*i]);
  printf("h%x\n", hex[i]); //for debugging
 }
}
void writeHex(char* hex, int length, FILE* file, long position) {
 fseek(file, position, SEEK_SET);
 fwrite(hex, sizeof(char), length, file);
}
int main(int argc, char** argv) {
 FILE* pic = fopen("hi.bmp", "w+b");
 const char* string = "f2";
 char hex[strlen(string)/2];
 stringToHex(string, hex);
 writeHex(hex, strlen(string)/2, pic, 0);
 fclose(pic);
 return 0;
}
I want it to save the hexadecimal number 0xf2 to a file (later I will have to write bigger/longer numbers though). The program prints out -
s66h36
And when I use hexedit to view the file I see the number '36' in it.
Why is my code not working? Thanks!
© Stack Overflow or respective owner