Reputation: 355
I have downloaded an image and it is saved in a std::string
.
Now I want to use/open it with following conditions:
typedef uint8_t byte //1 byte unsigned integer type.
static open(const byte * data, long size)
How do I cast from string
to byte*
?
/EDIT:
i have already tried this:
_data = std::vector<byte>(s.begin(), s.end());
//_data = std::vector<uint8_t>(s.begin(), s.end()); //also fails, same error
_p = &_data[0];
open(_p, _data.size())
but i get:
undefined reference to 'open(unsigned char const*, long)'
why does it interpret byte wrongly as char?!
/EDIT2: just to test it i changed to function call to
open(*_p, _data.size())
but then i get:
error: no matching function for call to 'open(unsigned char&, size_t)'
[...] open(const byte*, long int) <near match>
So the function is definitly found...
Upvotes: 1
Views: 15234
Reputation: 279255
Two possibilities:
1) the common one. On your system, char
is either 2's complement or else unsigned, and hence it is "safe" to read chars as unsigned chars, and (if char
is signed) the result is the same as converting from signed to unsigned.
In which case, use reinterpret_cast<const uint8_t*>(string.data())
.
2) the uncommon one. On your system, char
is signed and not 2's complement and hence for char *ptr
pointing to a negative value the result of *(uint8_t*)ptr
is not equal to (uint8_t)(*ptr)
. Then depending what open
actually does with the data, the above might be fine or you might have to copy the data out of a string and into a container of uint8_t
, converting as you go. For example, vector<uint8_t> v(string.begin(), string.end());
. Then use &v[0]
provided that the length is not 0 (unlike string, you aren't permitted to take a pointer to the data of an empty vector even if you never dereference it).
Non-2's-complement systems are approximately non-existent, and even if there was one I think it's fairly unlikely that a system on which char
was signed and not 2's complement would provide uint8_t
at all (because if it does then it must also provide int8_t
). So (2) only serves pedantic completeness.
why does it interpret byte wrongly as char
It isn't wrong, uint8_t
is a typedef for unsigned char
on your system.
Upvotes: 4