简体   繁体   English

C ++:如何将十六进制字符转换为无符号字符?

[英]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. 我有一个采用无符号字符的方法,但我想将其传递给0x01。

I know I can represent hex chars in strings by going "\\x01"... but that is still a signed char. 我知道我可以通过“ \\ x01”来表示字符串中的十六进制字符...但是那仍然是一个带符号的字符。

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: 另外,当强制转换只是对unsigned char的转换时,我会收到此错误:

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

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. 0x011相同,为正数,因此无论它是带符号的还是无符号的都没有关系,其值相同。

If you want to have an unsigned type on the literal, use 0x01u . 如果要在文字上使用无符号类型,请使用0x01u

Note that "\\x00" is an string constant (read: array of char), and not a single character constant. 请注意,“ \\ x00”是字符串常量(读取:char数组),而不是单个字符常量。

Use single quotes: '\\x00' is a character constant. 使用单引号:'\\ x00'是字符常量。

The type might be char, but that is automatically converted to unsigned char when needed. 该类型可能是char,但是在需要时会自动转换为unsigned char。 Some compilers might issue a warning though. 有些编译器可能会发出警告。

您可以使用boost::lexical_cast

unsigned char bar = boost::lexical_cast<unsigned char>( "\x71" );
void foo(unsigned char const * u);
...
foo( (unsigned char const *) "\x01");

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

I bet you can't send it \\x-01. 我敢打赌您不能发送\\ x-01。 Therefore you are sending it an unsigned int. 因此,您要向它发送一个未签名的int。

You can always test you your input before you send it to the func. 在将输入发送到函数之前,您始终可以对其进行测试。 If inp < 0 then send it back. 如果inp <0,则将其发送回。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM