获取十六进制字符串的字节长度的另一种方法
Alternate way to get the Byte Length of a Hex string
我创建了一个函数来计算传入十六进制字符串的字节长度,然后将该长度转换为十六进制。它首先将传入字符串的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();
}
相关文章:
- 只需要知道我在c ++中打印模式的方式是否有效,或者有另一种方法可以有效地做到这一点
- 如何在一种方法中创建对象并在另一种方法中使用它
- 常量静态成员函数:有另一种方法可用吗?
- 如何将程序从主发送到另一种方法
- 如何使用shared_ptr或推荐另一种方法(unique_ptr)
- 在C++编程中继续下一行的另一种方法是什么?
- 是否有另一种方法可以在不使用宏定义的情况下进行此操作
- 将带有参数的void方法传递给使用std ::函数和std :: bind c 的另一种方法
- C++:访问由另一种方法返回的向量的常量向量时出现分段错误
- 一个人如何将腋窝VEC/MAT作为REF论点传递给另一种方法
- Visual Studio 2003使用regex的另一种方法
- C++另一种方法计算平均值
- 在cuda中使用静态成员函数模板结构的另一种方法
- C++-使用循环的另一种方法
- 在C++03中初始化成员的另一种方法
- 获取十六进制字符串的字节长度的另一种方法
- 如何让一些派生类使用相同的方法,而另一些派生类则使用另一种方法
- 除以2的另一种方法是什么?
- 是否有另一种方法调用基方法从派生是虚拟的
- 在数据结构中保存成员的另一种方法