Search code examples
c++openglglut

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*. I am trying to convert a string to a 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. 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. Using a reinterpret_cast comes to mind, but I don't know how it works.


Solution

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

    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. 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

    Is the char 0xA4 positive or negative? It's neither. It's ñ. It's not a number at all. So signed vs. unsigned doesn't really matter. Make sense?