Skip to content

Instantly share code, notes, and snippets.

@sdkfz181tiger
Last active May 18, 2024 05:13
Show Gist options
  • Save sdkfz181tiger/c768a976c86883b3a0b008c122205e15 to your computer and use it in GitHub Desktop.
Save sdkfz181tiger/c768a976c86883b3a0b008c122205e15 to your computer and use it in GitHub Desktop.
C/C++課題ネタ10_文字列の操作
//==========
// 数値から文字列への変換
// 1, Compile
// g++ -std=c++17 -Wall -Wextra main.cpp
// 2, Run
// ./a.out
#include <math.h>
#include <stdio.h>
#include <string>
#include <vector>
using namespace std;
const string CODE = "0123456789ABCDEF";
string n2s(int num){
string str = "";
do{
str = char(CODE[num%16]) + str;
num = num>>4;
}while(0 < num);
return str;
}
int main(){
printf("Hello, Cpp!!\n");
// 16進数
const vector<int> nums = {0x7D, 0xAD, 0xF0, 0x0D};
for(auto num: nums){
const string str = n2s(num);
printf("Num: %d -> Str: %s\n", num, str.c_str());
}
return 0;
}
//==========
// 文字列から数値への変換
// 1, Compile
// g++ -std=c++17 -Wall -Wextra main.cpp
// 2, Run
// ./a.out
#include <math.h>
#include <stdio.h>
#include <string>
#include <vector>
using namespace std;
const string CODE = "0123456789ABCDEF";
string n2s(int num){
string str = "";
do{
str = char(CODE[num%16]) + str;
num = num>>4;
}while(0 < num);
return str;
}
unsigned int c2n(const char c){
if('0' <= c && c <= '9') return c - '0';
if('A' <= c && c <= 'F') return c - 'A' + 10;
if('a' <= c && c <= 'f') return c - 'f' + 10;
return -1;// Error
}
int main(){
printf("Hello, Cpp!!\n");
// 文字列
const vector<string> strs = {"7D", "AD", "F0", "0D"};
for(auto str: strs){
unsigned int num = 0;
for(size_t i=0; i<str.size(); i++){
num += c2n(str[i]);
if(i < str.size()-1) num = num<<4;
}
printf("Str: %s -> Num: %d -> Str: %s\n", str.c_str(), num, n2s(num).c_str());
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment