2

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

5
  • IMHO the best thing is to manage a uint8_t* in an explicit way (either by writing the individual bytes by means of bitshifts and explicit endianess or by resorting to unaligned integer load/store), possibly wrapped in a std::array<uint8_t>. Commented Aug 5, 2012 at 21:58
  • Though I still need it resulting in a string... Would it work to shift into a char that you later append to the string? Commented Aug 5, 2012 at 22:04
  • 4
    Why do you want this in a std::string? It's not a sequence of characters; it's an arbitrary array of bytes. So use a std::vector<uint8_t>. Commented Aug 5, 2012 at 22:07
  • "Note I DO NOT want the viewable binary representation but the actual binary data in the string" What does this mean? Commented Aug 5, 2012 at 22:38
  • I meant that I don´t want the printable string containing chars of "1" and "0" ("11111100 ... ") but the ascii (11111100) value. Commented Aug 5, 2012 at 22:44

3 Answers 3

3

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

1 Comment

Thanks! It was something like this I was looking for.
2
char buffer[1024];
// fill up buffer with whatever
char *end = afterLastChar;
std:string s(buffer, afterLastChar);

Comments

0

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

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.