1

I have, in a .txt file, a uint8_t array already formatted, like this:

0x4d, 0x5a, 0x90, 0x00, 0x03, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00,
0xb8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40,

What I need is to initialize it from C++ like so:

static const uint8_t binary[] = { 0x4d, 0x5a, 0x90, 0x00, 0x03, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xb8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, }

Honestly, I'm a bit new at C++.

JaMiT
  • 14,422
  • 4
  • 15
  • 31
DreamY
  • 13
  • 3

3 Answers3

1

If I understand your question correctly, you simply need to include your text file at the place of array declaration:

static const uint8_t binary[] = {
#include "array.txt"
};
Vlad Feinstein
  • 10,960
  • 1
  • 12
  • 27
1

If the text file is shown exactly as you have shown, AND you want to initialize the array at compile-time, then you could simply #include the file, eg:

static const uint8_t binary[] = {
#include "text.txt"
}

Otherwise, you will have to open the text file at runtime, such as with std::ifstream, read in its context and parse the byte values from it, and then allocate and populate your array dynamically, such as by using std::vector.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
0

Is the .txt file storing the hex values as bytes, or as 4 characters representing the hex values with literal commas and spaces?

If you're storing the actual hexadecimal values, the code becomes as simple as

#include <fstream>
#include <vector>

// input file stream
std::ifstream is("MyFile.txt"); 

// iterators to start and end of file
std::istream_iterator<uint8_t> start(is), end; 

// initialise vector with bytes from file using the iterators
std::vector<uint8_t> numbers(start, end); 
fortytoo
  • 452
  • 2
  • 11