开发者

Problem with writing a hexadecimal string

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, FI开发者_高级运维LE* 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!


When it processes "f", it converted it to the character f, which is ascii 102, which is hex 66. That's why you got the "s66" part of your answer.

%x prints out an integer in its hexadecimal representation.

I think you want sscanf( string, "%x", &hexInt )

That'll read in string as a hexadecimal string and save its value in the int hexInt.


It's not (at all!) apparent from your code what you really want to accomplish. You're starting with a string containing hexadecimal digits, and then (apparently) trying to convert that to hexadecimal...

Normally, you'd do something like this:

int x = 0xf2;

printf("%0x", x);


Using muddybruin's answer I built this-

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

void stringToHex(char* string, int* hex) {
    int i = 0;
    char tmpByte[3] = {'\0', '\0', '\0'};

    for(i = 0; i < strlen(string)/2; i++) {
        memcpy(tmpByte, &string[2*i], 2);
        sscanf(tmpByte, "%x", &hex[i]);
    }
}

void writeHex(int* hex, int length, FILE* file, long position) {
    int i = 0;

    fseek(file, position, SEEK_SET);
    for(i = 0; i < length; i++) {
        fwrite(&hex[i], sizeof(char), 1, file);
        fseek(file, -3/4*sizeof(int), SEEK_CUR);
    }
}

int main(int argc, char** argv) {
    FILE* pic = fopen("hi.bmp", "w+b");
    char* string = "424D460000000000000036000000280000000200000002000000010018000000000010000000130B0000130B000000000000000000000000AAAFFFFF0000FF000000FF000000";
    int* hex = calloc(1000, sizeof(int));

    stringToHex(string, hex);
    writeHex(hex, strlen(string)/2, pic, 0);

    fclose(pic);
    return 0;
}

Not the best code in the world, but it works :).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜