NullVoxPopuli
NullVoxPopuli

Reputation: 65133

C++: how do I convert hex char to unsigned char?

I have a method that takes unsigned chars, but I want to pass it 0x01.

I know I can represent hex chars in strings by going "\x01"... but that is still a signed char.

EDIT: some code:

kennys_hash((unsigned char const *)"\x00"); // the method call

the error:

src/main.cpp:88: error: invalid conversion from ‘const unsigned char*’ to ‘unsigned char’
src/main.cpp:88: error:   initializing argument 1 of ‘unsigned char kennys_hash(unsigned char)’

the method header:

unsigned char kennys_hash(unsigned char out)

ALso, when the cast is just to unsigned char, I get this error:

src/main.cpp:88: error: cast from ‘const char*’ to ‘unsigned char’ loses precision

Upvotes: 0

Views: 3259

Answers (6)

Björn Pollex
Björn Pollex

Reputation: 76788

You can use boost::lexical_cast:

unsigned char bar = boost::lexical_cast<unsigned char>( "\x71" );

Upvotes: 1

Sjoerd
Sjoerd

Reputation: 6875

Note that "\x00" is an string constant (read: array of char), and not a single character constant.

Use single quotes: '\x00' is a character constant.

The type might be char, but that is automatically converted to unsigned char when needed. Some compilers might issue a warning though.

Upvotes: 2

Naruto77
Naruto77

Reputation: 33

I bet you can't send it \x-01. Therefore you are sending it an unsigned int.

You can always test you your input before you send it to the func. If inp < 0 then send it back.

Upvotes: 0

harald
harald

Reputation: 6126

You can pass it an array of unsigned chars, like this:

unsigned char data[5] = {1, 2, 3, 4, 5};
func_that_takes_unsigned_chars(data, sizeof data);

Upvotes: 0

unwind
unwind

Reputation: 399803

0x01 is the same as 1, which is positive, and thus it doesn't matter if it's considered to be signed or unsigned, the value is the same.

If you want to have an unsigned type on the literal, use 0x01u.

Upvotes: 3

Erik
Erik

Reputation: 91270

void foo(unsigned char const * u);
...
foo( (unsigned char const *) "\x01");

Upvotes: 0

Related Questions