繁体   English   中英

在C中以十六进制读取文件

[英]Read file as hex in C

这是我当前的代码:

#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;
}

它工作正常,但是问题是我需要读取该文件,然后以十六进制形式保存在buffer(keyStorage->key)中。

这是一个文件示例:

6B53E460E5D944A1200BE51A91588B50D3E887081E5DA5F90ADD71CF88D83A3C469EDB56E6FD526A4946B781257FFC950367

这应该给您一个想法:

#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
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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