Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read numeric data as uint8_t [duplicate]

Tags:

c++

iostream

I have some human-readable numeric data in an istream. The values range from 0-255, and I want to store them in uint8_t. Unfortunately, if I try something like

uint8_t a, b;
stringstream data("124 67");
data >> a >> b;

then I end up with a == '1' and b == '2'. I understand that this is the desired behavior in many situations, but I want to end up with a == 124 and b == 67. My current workaround is to stream the data into ints, then copy them to the uint8_ts.

uint8_t a, b;
int a_, b_;
stringstream data("124 67");
data >> a_ >> b_;
a = a_;
b = b_;

Clearly this gets very cumbersome (and slightly inefficient). Is there a cleaner way of reading numeric (as opposed to character) uint8_t data using streams?

like image 424
Nicu Stiurca Avatar asked Aug 13 '14 02:08

Nicu Stiurca


1 Answers

You can't. uint8_t and int8_t are typedefs for unsigned char and signed char respectively. These types are treated as character types by iostreams and there's no way to change that behaviour.

Your second example is really the only way you can do this.

like image 175
goji Avatar answered Oct 11 '22 10:10

goji