简体   繁体   中英

Read file as hex in C

This is my current code:

#include "fileread.h"

typedef struct
{
    char Key[50];
    int KeyLen;
}   KeyStorage;

eKeyFileRes GetNewKeyFile(  char *path, UINT64 fileName, KeyStorage *keyStorage)
{
    char sbuf[1024];
    FILE* file;
    sprintf (sbuf, "%s\\%llu.dat", path, fileName);  
    file=fopen(sbuf, "r");

    if(file == NULL)
    {
        return KeyFileRes_NoKeyFound;
    }
    else 
    { 
        fread(keyStorage->Key,1,50, file);
        fseek(file, 0L, SEEK_END);
        keyStorage->KeyLen = ftell(file);
    }
    fclose(file);
    return  KeyFileRes_NewKeyFound;
}

It works fine, however The problem is that I need to read that file and then save in buffer(keyStorage->key) but in hex.

Here is a file example:

6B53E460E5D944A1200BE51A91588B50D3E887081E5DA5F90ADD71CF88D83A3C469EDB56E6FD526A4946B781257FFC950367

This should give you an idea:

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

int main() {    
  char string[] = "6B53E460E5D9";   // NUL terminated sample string
  int length = strlen(string);      // get length of sample string

  for (int i = 0; i < length; i += 2)
  {
    char tmp[3];    
    tmp[0] = string[i];                             // copy 2 chars
    tmp[1] = string[i+1];                           //   "
    tmp[2] = 0;                                     // put the NUL terminator
    int value = strtol(tmp, NULL, 16);              // transform hex string to value
    printf("%d  %02x  %d\n", i / 2, value, value);  // show results
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM