简体   繁体   English

如何将 const char* 转换为 const unsigned char*

[英]How do I cast a const char* to a const unsigned char*

I want to take advantage of this post to understand in more detail how unsigned and signed work regarding pointers.我想利用这篇文章更详细地了解未签名和已签名的指针是如何工作的。 The problem I am having is that I have to use a function from opengl called glutBitmapString which takes as parameter a void* and const unsigned char*.我遇到的问题是我必须使用来自 opengl 的一个名为glutBitmapString的函数,该函数将void*和 const unsigned char*.作为参数char*. I am trying to convert a string to a const unsigned c_string .我正在尝试将字符串转换为 const unsigned c_string

Attempt:尝试:

string var = "foo";
glutBitmapString(font, var.c_str());

However, that's not quiet right because the newly generated c_str is signed.但是,这并不安静,因为新生成的c_str已签名。 I want to stay away from casting because I think that will cause narrowing errors.我想远离铸造,因为我认为这会导致缩小错误。 I think that unsigned char and signed char is almost the same thing but both do a different mapping.我认为 unsigned char 和 signed char 几乎是一回事,但两者都做不同的映射。 Using a reinterpret_cast comes to mind, but I don't know how it works.我想到了使用 reinterpret_cast,但我不知道它是如何工作的。

I would use reinterpret_cast :我会使用reinterpret_cast

glutBitmapString(font, reinterpret_cast</*const*/unsigned char*>(var.c_str()));

it is a rare case where strict aliasing rule is not broken.严格的别名规则没有被破坏是一种罕见的情况。

Negative values will be interpreted as unsigned (so value + 256 ).负值将被解释为无符号(所以 value + 256 )。

In this particular case (and almost all others), signed vs. unsigned refer to the content pointed at by the pointer.在这种特殊情况下(以及几乎所有其他情况),有符号与无符号是指指针指向的内容。

unsigned char* == a pointer to (unsigned char(s)) unsigned char* == 指向 (unsigned char(s)) 的指针

signed char* == a pointer to (signed char(s))有符号字符* == 指向(有符号字符)的指针

Generally, no one is treating 0xFF as a numeric value at all, and signed vs. unsigned doesn't matter.通常,根本没有人将 0xFF 视为数值,并且有符号与无符号无关紧要。 Not always the case and sometimes with strings people sloppily use unsigned vs signed to refer to one type over another....but you're probably safe just casting the pointer.情况并非总是如此,有时对于字符串,人们草率地使用无符号与有符号来指代一种类型而不是另一种类型......但你可能只是投射指针是安全的。

If you're NOT safe casting the pointer, it means your data that is pointed to is invalid/is in the wrong format.如果您不安全地投射指针,则意味着您指向的数据无效/格式错误。

To clarify on unsigned char vs. signed char, check this out: https://sqljunkieshare.files.wordpress.com/2012/01/extended-ascii-table.jpg要澄清无符号字符与有符号字符,请查看: https : //sqljunkieshare.files.wordpress.com/2012/01/extended-ascii-table.jpg

Is the char 0xA4 positive or negative? char 0xA4 是正数还是负数? It's neither.两者都不是。 It's ñ .它是ñ It's not a number at all.这根本不是一个数字。 So signed vs. unsigned doesn't really matter.所以签名与未签名并不重要。 Make sense?有道理吗?

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

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