The function of translating a string into a sequence of bytes Returns a string incorrectly. If the string test is an expression with a comment, it shows 8

 char* str_to_binary (const char* str) { string bin; for (std::size_t i = 0; i < s.size(); ++i) { bitset<8> b(s.c_str()[i]); bin += b.to_string(); } char* c = new char[bin.length() + 1]; strcpy(c, bin.c_str()); // sizeof(c)/sizeof(char) return c; } 
  • What is the variable s ? I don't see her - Pavel Mayorov

2 answers 2

Your sizeof(c)/sizeof(char) expression is equal to the size of a pointer to char in char sizes, i.e. bytes. On a standard 32-bit platform, the pointer size is 4 bytes, on a 64-bit one - 8.

By the way, you pass const char * str to the function, and you work with something like string s , which is not declared anywhere ...

You can calculate the length of a string with a terminating null character (in C style) using the strlen(char*) function

  • And how then to return the number of characters in the array c ? - Herrgott
  • You yourself allocate bin.length() + 1 byte, and that's the size ... - Harry
  • bin.length() + 1 generally returns something like 1 or 2 . And about string s - copy - paste errors - Herrgott
  • What it returns is the second question :) What do you actually need? Imagine that there is an array of 10 char , in which the string "hello" written. What would you like to receive? 10 or 5? - Harry
  • one
    @Herrgott ошибки копипаста could be corrected by editing the question text. - αλεχολυτ

The @Harry answer explains why sizeof(c)/sizeof(char) , where c is a pointer, returns the size of the pointer type, and not the length of the C string that this pointer can refer to.

To completely avoid such errors, you can use std::string for I / O instead of char* . For example, to get bits of bytes from strings ("01" strings — representation of bytes in binary):

 #include <bitset> #include <climits> #include <string> template<class UnaryFunction> void str_to_bits(const std::string& str, UnaryFunction yield) { for (unsigned char byte : str) yield(std::bitset<CHAR_BIT>(byte).to_string()); } 

Call example:

 #include <iostream> int main() { str_to_bits("abcdefgh", [] (auto bits) { std::cout << bits << ' '; }); } 

auto in lambda supported only starting with c ++ 14:

 $ g++ -std=c++14 yield_bits.cxx && ./a.out 01100001 01100010 01100011 01100100 01100101 01100110 01100111 01101000 

The expected codes of letters in the English alphabet go in a row (1, 10, 11, 100, 101, etc. in the binary system).