C++ string to binary code / binary code to string - c++

I need to convert a string into a string with the binary code of the first string.
For the first part i used this: Fastest way to Convert String to Binary? Worked perfectly but i can't figure out a way to write it into a new string.
Here's the code i'm using so far:
for (size_t i = 0; i < outputInformations.size(); ++i)
{
cout << bitset<8>(outputInformations.c_str()[i]);
}
Output:
01110100011001010111001101110100011101010111001101100101011100100110111001100001011011010110010100001010011101000110010101110011011101000111000001100001011100110111001101110111011011110111001001100100
Is there a way to write this into a new string? So that i have a string called "binary_outputInformations" with the binary code inside it.

Are you looking for this ?
string myString = "Hello World";
std::string binary_outputInformations;
for (std::size_t i = 0; i < myString.size(); ++i)
{
bitset<8> b(myString.c_str()[i]);
binary_outputInformations+= b.to_string();
}
std::cout<<binary_outputInformations;
Output :
0100100001100101011011000110110001101111001000000101011101101111011100100110110001100100

Use std::ostringstream (and hopefully C++11):
#include <iostream>
#include <sstream>
#include <bitset>
std::string to_binary(const std::string& input)
{
std::ostringstream oss;
for(auto c : input) {
oss << std::bitset<8>(c);
}
return oss.str();
}
int main()
{
std::string outputInformations("testusername\ntestpassword");
std::string binary_outputInformations(to_binary(outputInformations));
std::cout << binary_outputInformations << std::endl;
}
Output:
01110100011001010111001101110100011101010111001101100101011100100110111001100001011011010110010100001010011101000110010101110011011101000111000001100001011100110111001101110111011011110111001001100100

Related

Store cout output into variable

How can I store the output from cout into a variable of string or character type?
I have written following code but it doesn't work:
#include<iostream>
#include<stdio.h>
using namespace std;
int main(){
string n;
n = (cout<<"\nHello world");
cout<<n;
return 0;
}
#include <sstream>
std::ostringstream a;
a << "Hello, world!";
std::string b = a.str(); // Or better, `std::move(a).str()`.
std::cout << b;
Other answers have shown you how to capture formatted output using a std::(o)stringstream object directly. But, if for some reason, you really need to capture the output of std::cout, then you can temporarily redirect std::cout to use a std::ostringstream's buffer, eg:
#include <iostream>
#include <sstream>
using namespace std;
int main(){
ostringstream oss;
auto cout_buff = cout.rdbuf(oss.rdbuf());
cout << "\nHello world";
cout.rdbuf(cout_buff);
string n = oss.str();
cout << n;
return 0;
}
Online Demo
Of course there's a way! But you have to use a different kind of stream:
std::ostringstream ss;
ss << "\nHello world";
std::string result = ss.str();
Also, in C++20, you can simply use std::format:
std::string n = std::format("Hello {}! I have {} cats\n", "world", 3);
// n == "Hello world! I have 3 cats\n"

convert a long string of characters to uint32_t or uint64_t in c++

I want to convert a string containing alphanumeric characters into either uint32_t or uint64_t.
Tried doing the following. But, I am getting "terminate called after throwing an instance of 'std::out_of_range' " error. Also, when the string is smaller in length, for example : string s = "hello", it works, but what if I want to convert a longer string into uint32_t or uint64_t.
#include <iostream>
#include <sstream>
#include <iomanip>
std::string string_to_hex(const std::string& in) {
std::stringstream ss;
ss << std::hex << std::setfill('0');
for (size_t i = 0; i < in.size(); ++i) {
ss << std::setw(2) << static_cast<unsigned int>(static_cast<unsigned char>(in[i]));
}
return ss.str();
}
int main() {
std::string s = "hello world, this 123";
std::string hex_str = string_to_hex(s);
uint32_t value = std::stoul(hex_str , nullptr, 16);
cout<<value<<endl;
}
Okay, so according to the comments given, is the following the best way to do it?
int main()
{
std::string s = "hello world, this 123";
std::hash<std::string> hashed_name;
uint32_t value = hashed_name(s);
cout<<value<<endl;
return 0;
}
This, strictly speaking, does what you need:
#include <iostream>
#include <string>
#include <unordered_map>
class Converter
{
public:
static int StringToInt(const std::string& s)
{
auto it = cache.find(s);
if (it != cache.end())
return it->second;
cache[s] = count;
lookup[count++] = s;
}
static std::string IntToString(unsigned i)
{
auto it = lookup.find(i);
if (it != lookup.end())
return it->second;
return "";
}
private:
static inline unsigned count = 0;
static inline std::unordered_map<std::string, int> cache;
static inline std::unordered_map<int, std::string> lookup;
};
int main() {
std::string s = "hello world, this 123";
int value = Converter::StringToInt(s);
std::cout << value << std::endl;
std::string s2 = Converter::IntToString(value);
std::cout << s2 << std::endl;
int value2 = Converter::StringToInt("hello world, this 123");
std::cout << value2 << std::endl;
}
Your issue is that the resultant hex_str is a MASSIVE number.
Specifically: 0x68656c6c6f20776f726c642c207468697320313233
You are converting every character to a two-digit hex value (i.e. one byte). Strings of size 4 (8 if using 64 bit int) or more is going to result in a number way too large to fit in your resultant uint32_t or uint64_t
See this GDB printout of your program
As Remy mentioned in the comments, look into hash algorithms.

Declaring an array of type String containing numbers with padding

I am trying to create an array of String that contain numbers. These numbers are the names of folders that I need to access. Currently I am declaring it as shown below:
String str1[] = { "001", "002", "003", "004", "005", "006", "007", "008", "009", "010", "011", "012", "013", "014", "015", "016", "017", "018", "019", "020", };
I have 124 folders and naming them in such fashion is tedious. Is there a better way to do this? I am working with C++.
You can use stringstreams and set the format options to fill the integer to a certain number of characters and set the filling character.
Edit: Ok my code doesn't begin with 1 but 0, but I'm sure you can figure that out :)
#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>
#include <vector>
using namespace std;
int main()
{
std::vector<std::string> strs;
for (int i = 0; i < 124; i++)
{
std::ostringstream os;
os << std::setfill('0') << std::setw(3) << i;
strs.push_back(os.str());
}
for (const auto& s : strs)
{
std::cout << s << "\n";
}
}
Live example: http://ideone.com/TEV2iq
use a stringstream and for loop.
Example:
uint32_t t150()
{
std::vector<std::string> strVec; // i.e. String str1[]
for (int i=1; i<125; ++i)
{
std::stringstream ss;
ss << std::setw(3) << std::setfill('0') << i;
strVec.push_back(ss.str());
}
for (int i=0; i<124; ++i)
std::cout << strVec[i] << std::endl;
return(0);
}
An alternative is something like:
std::string t150b(int i) {
std::stringstream ss;
ss << std::setw(3) << std::setfill('0') << i;
return (ss.str());
}
// not tested, and no range check
which returns the formatted string for the value i ... I imagine you have the loop at some higher level code.
Another alternative is to skip the vector, just build the string with white spaces between ... then fetch them like you fetch any file item ...
void t150c(std::stringstream& ss)
{
for (int i=1; i<125; ++i) {
ss << std::setw(3) << std::setfill('0') << i << " ";
// white space between values -------------------^^
}
}
Usage example:
{
std::stringstream ss;
t150c(ss); // 'fill' stream with desired strings
do {
if(ss.eof()) break;
std::string s;
ss >> s; // extract string one at a time
std::cout << s << std::endl; // and use
}while(1);
}
std::string str1[124];
for(int i = 1; i <= 124; i++){
str1[i-1] = convertTo3Digit(i);
}
Then just write the convertTo3Digit function to take the numerical value and format it into a 3-digit string.
Another less elegant way would be to format a column in excel to be three-digit numbers and generate 001-124 and then copy-paste into your static initializer. You can use regex to add the quotes and commas.

is there a way to parse a INT to string/char* without using a stream?

There are sooo many posts about converting from int to string but they all really involve either just printing to the screen, or using ostringstream.
I was using ostringstream, but my company doesnt want me to use any streams because it has horrid runtimes.
I was doing this in a C++ file.
my issue is that i was going to, over the course of execution create millions of streams, write to the buffers, and then copy content into a string, as such:
ostringstream OS;
os << "TROLOLOLOLOL";
std::string myStr = os.str();
There is redundancy as it is making this buffer then copying it all over. UGH!
In C++11:
string s = std::to_string(42);
I did a benchmark a couple of weeks ago, and got those results (using clang and libc++ shipped with current Xcode):
stringstream took 446ms
to_string took 203ms
c style took 170ms
With the following code:
#include <iostream>
#include <chrono>
#include <sstream>
#include <stdlib.h>
using namespace std;
struct Measure {
chrono::time_point<chrono::system_clock> _start;
string _name;
Measure(const string& name) : _name(name) {
_start = chrono::system_clock::now();
}
~Measure() {
cout << _name << " took " << chrono::duration_cast<chrono::milliseconds>(chrono::system_clock::now() - _start).count() << "ms" << endl;
}
};
int main(int argc, const char * argv[]) {
int n = 1000000;
{
Measure m("stringstream");
for (int i = 0; i < n; ++i) {
stringstream ss;
ss << i;
string s = ss.str();
}
}
{
Measure m("to_string");
for (int i = 0; i < n; ++i) {
string s = to_string(i);
}
}
{
Measure m("c style");
for (int i = 0; i < n; ++i) {
char buff[50];
snprintf(buff, 49, "%d", i);
string s(buff);
}
}
return 0;
}
In C++11 you have std::to_string. Although it probably uses the stringstream technique under the hoods.
You should take a look at the performance chart of boost::lexical_cast:
http://www.boost.org/doc/libs/1_52_0/doc/html/boost_lexical_cast/performance.html
It compares lexical_cast to stringstream (with and without construction) and scanf/printf.
In most cases boost::lexical_cast is faster than scanf, printf, std::stringstream.
Reusing the stringstream buffer. Note, this is not thread safe.
#include <sstream>
#include <iostream>
#include <string>
template<class T>
bool str_to_type(const char *str, T &value) {
static std::stringstream strm;
if ( str ) {
strm << std::ends;
strm.clear();
strm.setf(std::ios::boolalpha);
strm.seekp(0);
strm.seekg(0);
strm << str << std::ends;
strm >> value;
return !strm.fail();
}
return false;
}
int main(int argc, char *argv[])
{
int i;
if (!str_to_type("42", i))
std::cout << "Error" << std::endl;
std::cout << i << std::endl;
return 0;
}

files name with c++

in c++, for edit many files I use some similar to
#include<iostream>
#include<fstream>
#include<stdio.h>
using namespace std;
int main(){
char nombre[10];
int i;
ofstream salida;
for (i = 10; i < 20; i++) {
sprintf(nombre,"archivo%d.txt",i);
cout << nombre<<endl;
salida.open(nombre);
salida << 1000*i << endl;
salida.close();
}
return 0;
}
exist a better c++ way? for no use a char[10]
You can use the C++ std::ostringstream type:
for (int i = 10; i < 20; i++) {
std::ostringstream filename;
filename << "archivo" << i << ".txt";
salida.open(filename.str().c_str());
/* ... */
salida.close();
}
Most uses of sprintf can be replaced by std::ostringstream. You will need to include the <sstream> header file for this to work, though.
Hope this helps!
I think you are just looking for the c++ string class.
It can be found in std::string.
This is a pretty good reference.
Here you would use the string as:
#include <sstream>
...{
std::string fileName = "archivo";
std::string extension = ".txt";
...
salida.open((fileName + NumberToString(i) + extension).c_str());
...
}
template <typename T>
string NumberToString ( T Number )
{
stringstream ss;
ss << Number;
return ss.str();
}
The above is was recommended here.
boost::format would be very convenient replacement of sprintf. If this is what you are looking for.