0

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 
3
  • Can you be more specific? What is your input, what your desired output? Please provide code. Commented Mar 24, 2011 at 15:01
  • 1
    "\x00" is not char. its char*. it doesn't match "unsigned char out" Commented Mar 24, 2011 at 15:12
  • there's no sense to cast a pointer to a char. make it kennys_hash( "\x00"[0] ); or something Commented Mar 24, 2011 at 15:16

6 Answers 6

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

By using 0x01u, I can completely forget about strings altogether!~ thanks!
2

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.

Comments

1

You can use boost::lexical_cast:

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

Comments

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

Comments

0

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); 

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.