-2

Please kindly let me know if this question has been answered so I'll delete it.


I have a vector of character that represents a bit-string (or a bloom filter):

std::vector<unsigned char> bit_table_;

Question: How to convert the vector to a single bit-string?

Edit: in general a bloom filter is a bit-string:e.g. 10010101011000. In here it is represented as the above vector. I would like to convert it to a bit-string.

Aydin
  • 149
  • 6
  • 2
    Would you mind to define _single string_ further? Do you want a `std::string?` – πάντα ῥεῖ Sep 01 '18 at 19:09
  • Marked as a duplicate. Also, please do the googling yourself next time. It'll take less time from your side than writing a question, and won't required anyone to close-vote. –  Sep 01 '18 at 19:21
  • @paul sure I will do that next time. Please note that link does not solve my problem. See my comment below. – Aydin Sep 01 '18 at 19:22
  • @Blastfurnace Could you please see my comment to the answer (provided by @Derek) below. Let me know if it's not clear. Thanks! – Aydin Sep 01 '18 at 19:41
  • @Blastfurnace A long bit-string has been represented as the vector: bit_table_. I want to convert the vector to a string of bits. – Aydin Sep 01 '18 at 19:56
  • @Blastfurnace Yes and Yes. – Aydin Sep 01 '18 at 20:11

1 Answers1

3

The best C++ library for a bit string is the oddly-named bitset (odd because it's ordered, not unordered):

std::bitset<1024> bs;
for (int i = 0; i < bit_table_.size(); ++i) {
    bs[i] = bit_table_[i];
}

One convenient feature of bitset is that the whole thing can be printed at once, as a human-readable bit string, with the MSB on the left and the LSB on the right (e.g. “00101101” for the number 45):

std::cout << bs << std::endl;

Note that bitset needs to know the size (or at least the upper limit) of your bit string at compile time. (I picked 1024 simply to demonstrate that it can be much larger than your machine's word size.)

If your bit vector does fit within an unsigned long or unsigned long long, however, then you can rapidly get the packed bits out:

unsigned long bits = bs.to_ulong();
unsigned long long bits = bs.to_ullong();
Derek T. Jones
  • 1,800
  • 10
  • 18
  • thanks for the answer. But, the result vector is a concatenation of characters, not bitstring! So, it could not solve my problem. – Aydin Sep 01 '18 at 19:21
  • Ah, in that case you want a `bitset`. I'll edit my answer. – Derek T. Jones Sep 01 '18 at 19:41
  • thanks for your help, I managed to do it using mpz_import() and mpz_export() using GNU library. So the idea is that we transfer the vector elements into an array of char. Then, pass the array to the mpz_import and get one big integer value. To reverse the process, and get an array of char we pass an empty array and the big integer to mpz_export. – Aydin Sep 01 '18 at 21:31