获取十六进制字符串的字节长度的另一种方法

Alternate way to get the Byte Length of a Hex string

本文关键字:另一种 方法 字节 十六进制 字符串 获取      更新时间:2023-10-16

我创建了一个函数来计算传入十六进制字符串的字节长度,然后将该长度转换为十六进制。它首先将传入字符串的Byte Length指定给int,然后将int转换为字符串。在将传入字符串的字节长度分配给int后,我检查它是否大于255,如果大于255,我插入一个零,这样我就返回了2个字节,而不是3位。

我做以下事情:

1) 接受十六进制字符串并将数字除以2。

static int ByteLen(std::string sHexStr)
{
    return (sHexStr.length() / 2);
}

2) 接受十六进制字符串,然后使用itoa()将其转换为十六进制格式字符串

static std::string ByteLenStr(std::string sHexStr)
{
    //Assign the length to an int 
    int iLen = ByteLen(sHexStr);
    std::string sTemp = "";
    std::string sZero = "0";
    std::string sLen = "";
    char buffer [1000];
     if (iLen > 255)
     {
        //returns the number passed converted to hex base-16 
        //if it is over 255 then it will insert a 0 infront 
                //so to have 2 bytes instead of 3-bits
        sTemp = itoa (iLen,buffer,16);
        sLen = sTemp.insert(0,sZero);               
                return sLen;
     }
     else{
                return itoa (iLen,buffer,16);
     }
}

我把长度转换成十六进制。这似乎很好,但我正在寻找一种更简单的方式来格式化文本,就像我在C#中使用ToString("X2")方法一样。这是针对C++的,还是我的方法足够好?

以下是我在C#中的操作方法:

public static int ByteLen(string sHexStr)
        {
            return (sHexStr.Length / 2);
        }
        public static string ByteLenStr(string sHexStr)
        {
            int iLen = ByteLen(sHexStr);
            if (iLen > 255)
                return iLen.ToString("X4");
            else
                return iLen.ToString("X2");
        }

我的逻辑在C++中可能有点偏离,但C#方法对我来说已经足够好了。

谢谢你抽出时间。

static std::string ByteLenStr(std::string& sHexStr)
{
    int iLen = ByteLen(sHexStr);
    char buffer[16];
    snprintf(buffer, sizeof(buffer), (iLen > 255) ? "%04x" : "%02x", iLen);
    return buffer;
}

snprintf使用格式字符串和参数的变量列表来格式化缓冲区中的文本。我们使用%x格式代码将int参数转换为十六进制字符串。在这个例子中,我们有两个格式字符串可供选择:

  • iLen > 255时,我们希望数字为四位数%04x表示十六进制字符串的格式,开头最多四位为零填充
  • 否则,我们希望该数字为两位数%02x表示十六进制字符串的格式,最多两位零填充

我们使用三元运算符来选择我们使用的格式字符串。最后,iLen作为单个参数传递,该参数将用于提供由函数格式化的值。

对于不使用任何C函数的纯C++解决方案,请尝试使用std::stringstream来帮助您格式化:

static std::string ByteLenStr(std::string sHexStr)
{
    //Assign the length to an int 
    int iLen = ByteLen(sHexStr);
    //return the number converted to hex base-16 
    //if it is over 255 then insert a 0 in front 
    //so to have 2 bytes instead of 3-bits
    std::stringstream ss;
    ss.fill('0');
    ss.width((iLen > 255) ? 4 : 2);
    ss << std::right << std::hex << iLen;
    return ss.str();
}