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++.

0

3 Answers 3

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"
};
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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); 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.