简体   繁体   中英

c++ parsing hex char array efficiently

I'm trying to figure out how to most efficiently parse the following into Hex segments with c++ 98.

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

and want parse out 50 FF FE & F080 (assuming I know hexData will be in this format every time) into base 10. Yielding something like:

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

Here's one strategy.

  1. Copy the necessary characters one at a time to a temporary string.
  2. Use strtol to extract the numbers.

Program:

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

Output:

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

You can convert all string to number and then use bitwise operations to get any bytes or bits. Try this

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

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