| CodeGuru Home | VC++ / MFC / C++ | .NET / C# | Visual Basic | Newsletters | VB Forums | Developer.com |
|
|||||||
| C++ (Non Visual C++ Issues) Ask or answer C and C++ questions not related to Visual C++. This includes Console programming, Linux programming, or general ANSI C++. |
![]() |
|
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
#1
|
|||
|
|||
|
Conversion from signed string to unsigned
Any ideas for a more efficient and safer conversion from signed string to unsigned?
Code:
std::basic_string<unsigned char> string_to_unsigned(const std::string& s)
{
int size = s.size();
const char* p;
std::basic_string<unsigned char> output;
output.reserve(size);
if (size)
{
p = &s[0];
for (int i = 0; i < size; ++i)
{
output.push_back(*((const unsigned char*)p));
++p;
}
}
return output;
}
|
|
#2
|
|||
|
|||
|
Re: Conversion from signed string to unsigned
I do not know if this is faster, but it certainly is simpler:
Code:
inline std::basic_string<unsigned char> string_to_unsigned(const std::string& s)
{
return std::basic_string<unsigned char>(s.begin(), s.end());
}
__________________
C + C++ Compiler: MinGW port of GCC Build + Version Control System: SCons + Bazaar Look up a C/C++ Reference and learn How To Ask Questions The Smart Way Kindly rate my posts if you found them useful
|
|
#3
|
|||
|
|||
|
Re: Conversion from signed string to unsigned
That seems to be more sensible. Although, I didn't contemplate anything similar at first because I wasn't sure whether implicit conversions between class types were allowed in C++.
|
|
#4
|
|||
|
|||
|
Re: Conversion from signed string to unsigned
The only conversion required by laserlight's code is that a char be implicitly convertible to an unsigned char. Which it is.
|
![]() |
| Bookmarks |
|
||||||
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|