C++標準ライブラリは大変優れています,というのはいうまでもない....勿論boostを使わないとできないことも多々あるが,それでもまずC由来のライブラリと合わせてこの標準ライブラリを使いこなせるようになれば大抵のことは出来るはず.
strtol, strtod, strtof - 文字列から数値型に変換
strtol, strtod, strtof -これらの関数はそれぞれconst char*をそれぞれlong型,double型,float型に変換する.strtolは指定した底から10進数に変換することもできる.似たような関数にatoi,atof,atolがある(atodはない,atofはdoubleを返す)が,N進数パース等といった機能も含めるとstrto系のほうがお勧めだ.ちなみにヘッダはcstdlid. long longに変換するstrtoll,long doubleへのstrtold, unsigned long longへのstrtoullもちゃんとある.
Javaでは
それぞれLong.parseLong(), Double.parseDouble(), Float.parseFloat().
サンプル
O'reillyのC++ Cookbookのサンプルコードをほぼ引用したうえで,自作のmyhex2int()で16進数->10進数変換するコードを足してみた.底変換のコードはもっときれいにかけるはずだがご愛嬌.
#include <iostream>
#include <string>
#include <cstdlib>
#include <cmath>
#include <map>
using namespace std;
static map<char,unsigned int> nummap;
long hex2int(const string& hexStr){
char *offset;
if(hexStr.length() > 2) {
if(hexStr[0] == '0' && hexStr[1] == 'x')
return strtol(hexStr.c_str(), &offset,0);
}
return strtol(hexStr.c_str(),&offset,16);
}
static void init_map() {
for( char ch = 0x30;ch < 0x40;ch++ )
nummap[ch] = ch-0x30;
for( char ch = 0x61;ch < 0x67;ch++ )
nummap[ch] = ch-0x31;
}
long myhex2int(const string& hexStr){
double repeat = 0;
int t = 0;
init_map();
int sum = 0;
if(hexStr.length() > 2 && hexStr[0] == '0' && hexStr[1] == 'x') {
for(int i = hexStr.length() - 1,repeat = 0;i > 1;i--,repeat++){
sum += ( nummap[hexStr[i]] * pow(16.0,repeat) );
}
}
else {
for( int i = hexStr.length() - 1,repeat = 0;i >= 0;i--,repeat++){
sum += ( nummap[hexStr[i]] * pow(16.0,repeat) );
}
}
return sum;
}
int main() {
string str1 = "0x1234";
cout << hex2int(str1) << endl;
string str2 = "1234";
cout << hex2int(str2) << endl;
string str3 = "QAFG";
cout << hex2int(str3) << endl;
cout << "--- my(hex) ---" << endl;
cout << myhex2int(str1) << endl;
cout << myhex2int(str2) << endl;
return EXIT_SUCCESS;
}
0 件のコメント:
コメントを投稿