简体   繁体   English

C ++:包含十六进制值的格式字符串

[英]C++: Format String Containing Hex Value

Working with C++ on Visual Studio 2010. 在Visual Studio 2010上使用C ++。

Trying to come up with a robust function that will take a hex value as string and size as integer and then output the formatted hex value. 尝试提出一个健壮的函数,它将十六进制值作为字符串,大小为整数,然后输出格式化的十六进制值。

For eg, 例如,

If the input string is "A2" and size is 1, then the output is "0xA2" 如果输入字符串为“A2”且大小为1,则输出为“0xA2”

If the input string is "800" and size is 2, then the output is "0x0800" 如果输入字符串为“800”且大小为2,则输出为“0x0800”

If the input string is "DEF" and size is 4, then the output is "0x00000DEF" 如果输入字符串为“DEF”且大小为4,则输出为“0x00000DEF”

If the input string is "00775" and size is 4, then the output is "0x00000775" 如果输入字符串为“00775”且大小为4,则输出为“0x00000775”

If the input string is "FB600" and size is 3, then the output is "0x0FB600" 如果输入字符串为“FB600”且大小为3,则输出为“0x0FB600”

The basic idea is, multiply size by 2 and then if the string length is less than that, then add leading zeros to the hex value and then append it with "0x". 基本思想是,将size乘以2,然后如果字符串长度小于该值,则将前导零添加到十六进制值,然后将其附加为“0x”。

"0x" is appended irrespective of whether leading zeros are added. 无论是否添加前导零,都附加“0x”。

As you see in 1st example, there's no zeros to add as the string already contains 2 characters. 正如您在第一个示例中所看到的,由于字符串已包含2个字符,因此无需添加零。

I came up with below function, but it's having memory corruption. 我提出了以下功能,但它有内存损坏。 Also when i try to process large amount of data by calling this function few hundrend times, it crashes. 此外,当我尝试通过调用此函数几个时间来处理大量数据时,它崩溃了。 Seems my logic has memory holes in it. 似乎我的逻辑中有记忆漏洞。

So am hoping that someone can come up with a robust intelligent code for this function. 所以我希望有人能为这个功能提出一个强大的智能代码。

What i tried: 我尝试了什么:

void formatHexString(char* inputHex, int size, char* outputFormattedHex)
{
    int len = size * 2;
    int diff = len - strlen(inputHex);
    char * tempHex = new char [diff + 2]; //"2" is for holding "0x"
    tempHex[0] = '0';
    tempHex[1] = 'x';

    if (len > strlen(inputHex))
    {

        for (int i = 2; i < ((len - strlen(inputHex)) + 2); i++)
        {
            tempHex[i] = '0';

        }

    }

    strcat(tempHex, inputHex);
    sprintf(outputFormattedHex, "%s", tempHex);

    delete [] tempHex;

    cout <<outputFormattedHex <<endl;
}


int main 
{
    char bbb1[24];
    formatHexString("23", 1, bbb1);
    char bbb2[24];
    formatHexString("A3", 2, bbb2);
    char bbb3[24];
    formatHexString("0AA23", 4, bbb3);
    char bbb4[24];
    formatHexString("7723", 4, bbb4);
    char bbb5[24];
    formatHexString("AA023", 4, bbb5);
    return 0;
}

UPDATED: 更新:

I cannot modify the arguments to original function as this function is called from a different application. 我无法修改原始函数的参数,因为此函数是从其他应用程序调用的。 So i modified my original function with your code, but this is not working. 所以我用你的代码修改了我原来的功能,但这不起作用。 Any ideas? 有任何想法吗?

void formatHexString(char* inputHex, int size, char* outputFormattedHex)
{
    string input(inputHex);
    std::size_t const input_len(input.length());

    if (!size || (size * 2 < input_len))
        size = input_len / 2 + input_len % 2;

    std::stringstream ss;
    ss << "0x" << std::setw(2 * size) << std::setfill('0') << input;
    sprintf(outputFormattedHex, "%s", ss.str());
}
#include <iostream>
#include <sstream>
#include <iomanip>
#include <string>
#include <cstddef>

std::string formatHexString(std::string const & input, std::size_t size = 0)
{
    std::size_t const input_len(input.length());

    // always round up to an even count of digits if no size is specified
    // or size would cause the output to be truncated
    if (!size || (size * 2 < input_len))
        size = input_len / 2 + input_len % 2;

    std::stringstream ss;
    ss << "0x" << std::setw(2 * size) << std::setfill('0') << input;
    return ss.str();
}

int main()
{
    std::cout << formatHexString(   "23") << '\n'
              << formatHexString(   "A3", 2) << '\n'
              << formatHexString( "AA23", 4) << '\n'
              << formatHexString( "7723", 4) << '\n'
              << formatHexString("AA023", 4) << '\n';
}

Solution without std::stringstream : 没有std::stringstream解决方案:

#include <string>
#include <cstddef>

std::string formatHexString(std::string const & input, std::size_t size = 0)
{
    std::size_t const input_len(input.length());

    // always round up to an even count of digits if no size is specified
    // or size would cause the output to be truncated
    if (!size || (size * 2 < input_len))
        size = input_len / 2 + input_len % 2;

    std::string result("0x");

    for (std::size_t i = 0, leading_zeros = size * 2 - input_len; i < leading_zeros; ++i)
        result += '0';

    result += input;
    return result;
}

Updated: 更新:

#define  _CRT_SECURE_NO_WARNINGS

#include <iostream>
#include <string>
#include <iomanip>
#include <sstream>
#include <cstddef>
#include <cstdio>

void formatHexString(char const * inputHex, int size, char * outputFormattedHex)
{
    int const input_len(std::strlen(inputHex));

    if (!size || (size * 2 < input_len))
        size = input_len / 2 + input_len % 2;

    std::stringstream ss;
    ss << "0x" << std::setw(2 * size) << std::setfill('0') << inputHex;
    std::strcpy(outputFormattedHex, ss.str().c_str());
}

int main()
{
    char output[24];
    formatHexString("23", 1, output);
    std::cout << output << '\n';

    formatHexString("A3", 2, output);
    std::cout << output << '\n';

    formatHexString("0AA23", 4, output);
    std::cout << output << '\n';

    formatHexString("7723", 4, output);
    std::cout << output << '\n';

    formatHexString("AA023", 4, output);
    std::cout << output << '\n';
}

It is unclear from your question, what you expect to happen with leading zeros on the input: Ie either input "00000000EA" Size 2 turns to "00EA", or it keeps all its leading zeros. 从您的问题中不清楚,您对输入的前导零的期望是什么:即输入“00000000EA”大小2变为“00EA”,或者保持其所有前导零。

This simple solution is for both cases (bTrim = true, for the 1st case): 这个简单的解决方案适用于两种情况(bTrim = true,对于第一种情况):

#include <string>

void formatHexString(std::string & strHex, unsigned int nSize, bool bTrim = true) 
{
    if (bTrim) // Trim leading-zeros:
        strHex = strHex.substr(strHex.find_first_not_of('0'));

    if (nSize > strHex.length()) // Pad with leading-zeros to fit nSize:
        strHex.insert(0, std::string(nSize - strHex.length(), '0').c_str());

    strHex.insert(0, "0x"); // Insert prefix
}

- -

If it's important to keep the original signature, wrap the above formatHexString with: 如果保留原始签名很重要,请将以上formatHexString包装为:

void formatHexString(char* inputHex, int size, char* outputFormattedHex)
{
    std::string strHex(inputHex);
    formatHexString(strHex, size * 2);
    strcpy_s(outputFormattedHex, strHex.length()+1, strHex.c_str()); // Visual Studio
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM