文字通り、あなたの質問を取り上げ、"FFFFFFFFFFFF"
の文字リテラル値から"\xFF\xFF\xFF\xFF\xFF\xFF"
という目標リテラル値に変換する方法に集中します(意図しない)。ここで
は、あなたが探しているものを達成するために一つの方法です:
#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>
int main()
{
std::string input = "FFFFFFFFFFFF"; // << Let's suppose this is given from the GUI
std::istringstream iss(input);
std::string output;
std::string sbyte;
while(iss >> std::setw(2) >> sbyte) {
std::cout << sbyte << std::endl;
std::istringstream iss2(sbyte);
unsigned u;
iss2 >> std::hex >> u;
output += (unsigned char)u;
}
// std::string::data() contains the resulting byte values:
for(unsigned char x : output) {
std::cout << std::hex << "\\x" << std::setw(2) << std::setfill('0')
<< (unsigned)x;
}
std::cout << std::endl;
}
は出力:
FF
FF
FF
FF
FF
FF
\xff\xff\xff\xff\xff\xff
あなたはstd::setw()
を使用して入力フィールドの幅を制御することができLive Demo
を参照してください。上記のように。
注:
これは明らかにstd::string
で動作しますが、前者std::setw(2)
ディレクティブで直接unsigned u;
を使用していない:
#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>
int main()
{
std::string input = "FFFFFFFFFFFF";
std::istringstream iss(input);
std::string output;
unsigned u;
while(iss >> std::setw(2) >> std::hex >> u) {
std::cout << std::hex << std::setw(2) << std::setfill('0') << u << std::endl;
output += (unsigned char)u;
}
for(unsigned char x : output) {
std::cout << std::hex << "\\x" << std::setw(2) << std::setfill('0')
<< (unsigned)x;
}
std::cout << std::endl;
}
Live Demo
1.ループ内でstd::string::substr()
を使用して入力文字列を分割することもできます。
Cタグはなぜですか? –
必要なのは、16進バイトを表す文字列を、表現されたバイト配列に変換することだけです。 Googleはそれを行う方法を知っています。 –
これは実際には文字列から文字列への質問ですか、それとも文字列が指定する整数値が必要なのでしょうか? –