string - How to convert int to binary and concatenate as char in C++ -
i have 2 values, 0 , 30, need store it's binary representation on 1 byte each. like:
byte 0 = 00000000
byte 1 = 00011110
and concatenate them on string print ascii 0 (null) , 30 (record separator). so, not print "030", can't right here , neither command can print properly. know not nice things print.
i doing this:
string final_message = static_cast<unsigned char>(bitset<8>(0).to_ulong()); final_message += static_cast<unsigned char>((bitset<8>(answer.size())).to_ulong()); // answer.size() = 30 cout << final_message << endl;
not sure if it's right, never worked bitset since now. think it's right server receives messages keep telling me numbers wrong. i'm pretty sure numbers need 0 , 30 on order, so, part i'm not sure how works 3 lines, i'm putting question here.
those 3 lines right? there's better way that?
a byte (or char
) holds single 8-bit value, , value same whether "view" in binary format, in decimal format, or character printed on console. it's way @ it.
see following example. first 2 examples byte1
, byte2
referred in question. unfortunately, won't see on console. therefore added example, illustrates 3 ways of viewing same value 65
in different ways. hope helps.
int main(){ char byte1 = 0b00000000; char byte2 = 0b00011110; std::cout << "byte1 'int value': " << (int)byte1 << "; , character: " << byte1 << endl; std::cout << "byte2 'int value': " << (int)byte2 << "; , character: " << byte2 << endl; char a1 = 65; char a2 = 'a'; char a3 = 0b001000001; std::cout << "a1 'int value': " << (int)a1 << "; , character: " << a1 << endl; std::cout << "a2 'int value': " << (int)a2 << "; , character: " << a2 << endl; std::cout << "a3 'int value': " << (int)a3 << "; , character: " << a3 << endl; return 0; }
output:
byte1 'int value': 0; , character: byte2 'int value': 30; , character: a1 'int value': 65; , character: a2 'int value': 65; , character: a3 'int value': 65; , character:
Comments
Post a Comment