[英]How to convert a string to a long or another string of ascii values?
在C ++中,如何將ASCII字符串(不超過5個元素)轉換為ASCII值或下面的long字符串?
str = "ABCDE"; --> ascii_value_str = "6566676869";
要么
str = "ABCDE"; --> long_int = 6566676869;
遍歷字符串"ABCDE"
,並將每個元素轉換為其ascii, ascii_value_str
使用std::to_string
添加到字符串ascii_value_str
for( const auto& ch: str )
{
ascii_value_str += std::to_string( (int) ch );
}
要轉換為您的long_int
,只需使用std::atol
long int long_int = std::atol( ascii_value_str .c_str() );
您可以只接受每個字符並將其轉換為int:
int aval = (int) str[i];
現在,您可以通過基本乘法將其轉換為long,或使用to_string
函數將其轉換為字符串。
如果您使用的是c++11
這將很容易編寫代碼,因為to_string()
函數可用於c++11
更高版本。 現在,您要做的就是使用其ASCII值。
看一下代碼片段:
1將String轉換為ASCII值字符串
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ", output;
for(int i=0; i<str.length(); i++) {
output += to_string((int)str[i]);
}
cout<< output << endl;
return 0;
}
2將字符串轉換為long int的ASCII值,但要注意long int的范圍。 對於長輸入字符串 ,您可能會得到錯誤的答案,現在代碼是。
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "xyz";
long int output = 0;
for(int i=0; i<str.length(); i++) {
if(str[i]/100) { // three digit ASCII Value
output = 1000*output + str[i];
} else if(str[i]/10) { // two digit ASCII Value
output = 100*output + str[i];
} else { // one digit ASCII Value
output = 10*output + str[i];
}
}
cout<< output << endl;
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.