如何为C ++中的十六进制字符的每个字节从十六进制字符串创建附加的0x十六进制字符串?

问题描述 投票:-1回答:1

尝试转换以下我的go代码问题

How to create a 0x appended hex string from a hex string for each byte of hex characters in golang?

对于C ++-但完全迷失了。

#include <iostream> 
#include <string> 
using namespace std; 

// Function to append 0x
void appendX(string str) 
{ 
    // Appends 1 occurrences of "X" to str 
    str.append(1, 'X'); 
    cout << "Modified append() : "; 
    cout << str; 

} 


int main() 
{ 
    string str("01234567891011121314151617181920"); 

    cout << "String : " << str << endl; 
    appendX(str); 

    return 0; 
} 

c++ hex
1个回答
0
投票

您的函数appendX()将仅在输入字符串的末尾附加一个'X',正如您的注释中也所说的。

但是,如果您尝试在字符串中的每个十六进制字节后附加“ 0x”(如您提到的GO语言问题中所述),则应在输入字符串中的每2个字符后附加“ 0x”。请尝试以下:

void appendX(String str) 
{ 
    String outstr;
    for(int i=0;i<str.size();i=i+2)
    {   
        outstr.append("0x"); 
        outstr.append(str,i,2);
    }
    cout << "Modified append() : "; 
    cout << outstr; 
} 
© www.soinside.com 2019 - 2024. All rights reserved.