0

着信 16 進文字列のバイト長をカウントし、その長さを 16 進数に変換する関数を作成しました。最初に着信文字列のバイト長を int に割り当て、次に int を文字列に変換します。着信文字列のバイト長を int に割り当てた後、255 を超えているかどうかを確認し、255 を超えている場合は、3 ビットではなく 2 バイトが返されるようにゼロを挿入します。

私は次のことを行います:

1) 16 進文字列を受け取り、数値を 2 で除算します。

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

2) 16 進文字列を受け取り、itoa() で 16 進形式の文字列に変換します。

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);
     }
}

長さを 16 進数に変換します。これはうまくいくようですが、ToString("X2") メソッドを使用して C# で行うように、テキストをフォーマットするより簡単な方法を探しています。これは 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# の方法で十分です。

お時間をいただきありがとうございます。

4

2 に答える 2

1

C 関数を使用しない純粋な C++ ソリューションのstd::stringstream場合は、書式設定に役立つ a を使用してみてください。

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();
}
于 2013-08-01T00:30:21.200 に答える