-2

I have two values, 0 and 30, I need to store it's binary representation on one byte for each. Like:

byte 0 = 00000000

byte 1 = 00011110

and then concatenate them on a string that will print the ASCII for 0 (NULL) and for 30 (Record Separator). So, not print "030", but something I can't really right here and neither the command can print properly. I know those are not nice things to print.

I was doing like 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()); // where answer.size() = 30
cout << final_message << endl;

Not sure if it's right, I never worked with bitset since now. I think it's right but the server that receives my messages keep telling me that the numbers are wrong. I'm pretty sure that the numbers I need are 0 and 30 on that order, so, as the only part I'm not sure how it works are those three lines, I'm putting this question here.

Those three lines are right? There's a better way to do that?

バカです
  • 175
  • 2
  • 4
  • 18

2 Answers2

1

A byte (or a char) holds a single 8-bit value, and the value is the same whether you "view" it in a binary format, in a decimal format, or as a character to be printed on the console. It's just the way you look at it.

See the following example. The first two examples byte1 and byte2 are those referred in your question. Unfortunately, you won't see much on the console. Therefore I added another example, which illustrates three ways of viewing the same value 65 in different ways. Hope it helps.

int main(){

    char byte1 = 0b00000000;
    char byte2 = 0b00011110;

    std::cout << "byte1 as 'int value': " << (int)byte1 << "; and as character: " << byte1 << endl;
    std::cout << "byte2 as 'int value': " << (int)byte2 << "; and as character: " << byte2 << endl;

    char a1 = 65;
    char a2 = 'A';
    char a3 = 0b001000001;

    std::cout << "a1 as 'int value': " << (int)a1 << "; and as character: " << a1 << endl;
    std::cout << "a2 as 'int value': " << (int)a2 << "; and as character: " << a2 << endl;
    std::cout << "a3 as 'int value': " << (int)a3 << "; and as character: " << a3 << endl;

    return 0;
}

Output:

byte1 as 'int value': 0; and as character: 
byte2 as 'int value': 30; and as character: 
a1 as 'int value': 65; and as character: A
a2 as 'int value': 65; and as character: A
a3 as 'int value': 65; and as character: A
Stephan Lechner
  • 34,891
  • 4
  • 35
  • 58
0

The line

string final_message = static_cast<unsigned char>(bitset<8>(0).to_ulong());

does not compile. And obviously, there is no need for bitset here as you are essentially juts add extra conversions in the path.

If I split the line above in 2 and use +=, the resulting string as a size of 2 and contain characters with values of 0 and 30 (I have inspected in using the debugger).

So I don't know what is your problem as it appears to do what you want...

Phil1970
  • 2,605
  • 2
  • 14
  • 15