Getting a byte value using stringstream

允我心安 提交于 2019-12-05 08:12:09

The most C++-ish way is certainly to parse the value properly by reading into another integral type, and then cast to a byte type (since reading into a char will never parse – it will always just read the next character):

typedef unsigned char byte_t;

unsigned int value;
ss >> value;
if (value > numeric_limits<byte_t>::max()) {
    // Error …
}

byte_t b = static_cast<byte_t>(value);

I’ve used unsigned int since that’s the most natural, although unsigned short would of course also work.

A char will always do that. You need to read an int (or float or double, etc) or else the wrong 'formatter' will be called.

unsigned char c;
unsigned int i;
ss >> i;
c = i;

Subtract '0' from it:

cout << (int) (c - '0') << endl;

'0' has a value of 48, so therefore 49 - 48 = 1

Matt Edlefsen
stringstream ss( "1" );
unsigned char c;
{
    unsigned int i;
    ss >> i;
    c = i;
}
cout << static_cast<int>(c) << endl;

Will work. You could also do some unsafe pointer stuff but I would just go with the above.

That's because string constants in C++ are treated like text.
Two options:

  • Encode the string using escaped numbers:

    • Octal Numbers: \0<d>{1,3}
    • Hex Numbers: \0x<d>{2}

    std::stringstream( "\01\02\03\04\0xFF");

  • Or build an array of char and initialize it using numbers:

    char data[] = { 0, 1, 2,3 ,4, 255 };

How about:

#include <iostream>
#include <sstream>

using namespace std;

int main(int argc, char** argv)
{
    char x[] = {1,0};
    stringstream ss( x);

    unsigned char c;
    ss >> c;

    cout << (int) c << endl;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!