I'm trying to convert a library of character manipulation from PHP to C++.
1) I've used static_cast<char>()
to replace all single chr()
functions (applied only to a single char, ie: PHP: $out = chr(50); => C++: std::string s = static_cast<char>(50)
).
Is this correct?
2) Given the following PHP code :
$crypt = chr(strval(substr("5522446633",0,2)));
In this snippet, we extract 2 char from the string "5522446633", and "get their string values" (PHP manual) from the function strval()
.
I know how to get the (integer) value from one char in C++, but how can I do with two chars?
How can I translate this snippet to C++?
The following code is equivalent to your php code:
#include <iostream>
#include <string>
std::string convert(const std::string& value)
{
size_t pos;
try
{
std::string sub = value.substr(0,2);
int chr = std::stoi(sub, &pos);
if (pos != sub.size())
{
return "";
}
return std::string(1, static_cast<char>(chr & 255));
}
catch ( std::exception& )
{
return "";
}
}
int main()
{
std::cout << convert("5522446633") << "\n";
}