user1432032
user1432032

Reputation: 155

build a binary string c++

How do I build a binary string in c++?

I want to have it in this format:

  std::string str = signed long (4bytes) "fill out zeros" 0x000 (8bytes) signed long (4bytes)

Note I DO NOT want the viewable binary representation but the actual binary data in the string

Upvotes: 2

Views: 3304

Answers (3)

Kerrek SB
Kerrek SB

Reputation: 476940

For your specific application:

std::string data(12, 0);  // construct string of 12 null-bytes

int32_t x, y;  // populate

char const * const p = reinterpret_cast<char const *>(&x);
char const * const q = reinterpret_cast<char const *>(&y);

std::copy(p, p + 4, data.begin()    );
std::copy(q, q + 4, data.begin() + 8);

Upvotes: 3

Joel Falcou
Joel Falcou

Reputation: 6357

Use std::vector< uint8_t >, this is not a string

Upvotes: 0

walrii
walrii

Reputation: 3522

char buffer[1024];
// fill up buffer with whatever
char *end = afterLastChar;
std:string s(buffer, afterLastChar);

Upvotes: 2

Related Questions