c ++有效地解析hex char数组

时间:2015-09-17 04:44:44

标签: c++ parsing hex

我正在试图弄清楚如何使用c ++ 98最有效地将以下内容解析为十六进制段。

//One lump, no delemiters
char hexData[] = "50FFFEF080";

并希望解析50 FF FE& F080(假设我知道hexData将每次都采用这种格式)到基数10.产生类似的东西:

var1=80
var2=255
var3=254
var4=61568

3 个答案:

答案 0 :(得分:2)

这是一个策略。

  1. 将必要的字符一次复制到临时字符串。
  2. 使用strtol提取数字。
  3. 程序:

    #include <stdio.h>
    #include <stdlib.h>
    
    int main()
    {
       char hexData[] = "50FFFEF080";
       int i = 0;
       int var[4];
       char temp[5] = {};
       char* end = NULL;
       for ( i = 0; i < 3; ++i )
       {
          temp[0] = hexData[i*2];
          temp[1] = hexData[i*2+1];
          var[i] = (int)strtol(temp, &end, 16);
          printf("var[%d]: %d\n", i, var[i]);
       }
    
       // The last number.
       temp[0] = hexData[3*2];
       temp[1] = hexData[3*2+1];
       temp[2] = hexData[3*2+2];
       temp[3] = hexData[3*2+3];
       var[3] = (int)strtol(temp, &end, 16);
       printf("var[3]: %d\n", var[3]);
    
       return 0;
    }
    

    输出:

    var[0]: 80
    var[1]: 255
    var[2]: 254
    var[3]: 61568
    

答案 1 :(得分:1)

您可以将所有字符串转换为数字,然后使用按位运算来获取任何字节或位。试试这个

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

int main()
{
   char hexData[] = "50FFFEF080";
   uint64_t number; // 64bit number
   // conversion from char-string to one big number
   sscanf(hexData, "%llx", &number); // read as a hex number
   uint64_t tmp = number; // just a copy of initial number to make bitwise operations
   // use masks to get particular bytes
   printf("%lld \n", tmp & 0xFFFF); // prints last two bytes as decimal number: 61568
   // or copy to some other memory
   unsigned int lastValue = tmp & 0xFFFF; // now lastValue has 61568 (0xF080)
   tmp >>= 16; // remove last two bytes with right shift
   printf("%lld \n", tmp & 0xFF); // prints the last byte 254
   tmp >>= 8; // remove lass byte with right shift
   printf("%lld \n", tmp & 0xFF); // prints 255
   tmp >>= 8; // remove lass byte with right shift
   printf("%lld \n", tmp & 0xFF); // prints 80
   return 0;
}

答案 2 :(得分:1)

#include <iostream>
#include <string>

int main() { 

    std::istringstream buffer("50FFFEF080");

    unsigned long long value;

    buffer >> std::hex >> value;

    int var1 = value & 0xFFFF;
    int var2 = (value >> 16) & 0xFF;
    int var3 = (value >> 24) & 0xFF;
    int var4 = (value >> 32) & 0xFF;    

    return 0;
}