LoginSignup
0
2

More than 3 years have passed since last update.

16進数文字列をバイナリに変換

Last updated at Posted at 2017-03-14

ただのメモ.
16進数文字列をバイナリに変換

#include <stdio.h>
#include <ctype.h>  //  isxdigit

// std::string bin2hex(const std::string& input)
// {
//     std::string res;
//     const char hex[] = "0123456789ABCDEF";
//     for(auto sc : input)
//     {
//         unsigned char c = static_cast<unsigned char>(sc);
//         res += hex[c >> 4];
//         res += hex[c & 0xf];
//     }
//
//     return res;
// }

const char * hex2bin(const char *hex, char *bin, size_t binsize) {
    if (hex && bin) {
        for (; binsize && isxdigit(hex[0]) && isxdigit(hex[1]); hex += 2, bin += 1, binsize -= 1) {     //  fujitanozomu さんの指摘を適用
            int r = sscanf_s(hex, "%2hhx", bin);                                                          //  shiracamus さんの指摘を適用
            if (r != 1) {
                break;
            }
        }
    }

    return hex;
}
#include <tchar.h>
#include <assert.h>

int main()
{
    char buf[80];
    const char * hexPriv = "b91c37cd87a0a66fd0c22eeac1bbac277db47f792310e3a9bb3ebd220fa72a59";
    const char * hexPub = "04daa7c6653f3e1ef969550c1018a1dd2d534d5169f155a8583d79abac1aca9e0d93cdc2a6f8368cf6d703f96dfd7cdb0b3aee8514d8c0225f8732dae79f487578";
    const unsigned char binPriv[] = { 0xb9, 0x1c, 0x37, 0xcd, 0x87, 0xa0, 0xa6, 0x6f, 0xd0, 0xc2, 0x2e, 0xea, 0xc1, 0xbb, 0xac, 0x27, 0x7d, 0xb4, 0x7f, 0x79, 0x23, 0x10, 0xe3, 0xa9, 0xbb, 0x3e, 0xbd, 0x22, 0x0f, 0xa7, 0x2a, 0x59, };
    const unsigned char binPub[] = { 0x04, 0xda, 0xa7, 0xc6, 0x65, 0x3f, 0x3e, 0x1e, 0xf9, 0x69, 0x55, 0x0c, 0x10, 0x18, 0xa1, 0xdd, 0x2d, 0x53, 0x4d, 0x51, 0x69, 0xf1, 0x55, 0xa8, 0x58, 0x3d, 0x79, 0xab, 0xac, 0x1a, 0xca, 0x9e, 0x0d, 0x93, 0xcd, 0xc2, 0xa6, 0xf8, 0x36, 0x8c, 0xf6, 0xd7, 0x03, 0xf9, 0x6d, 0xfd, 0x7c, 0xdb, 0x0b, 0x3a, 0xee, 0x85, 0x14, 0xd8, 0xc0, 0x22, 0x5f, 0x87, 0x32, 0xda, 0xe7, 0x9f, 0x48, 0x75, 0x78, };

    const char *p;
    p = hex2bin(hexPriv, buf, sizeof(buf));
    assert(p == hexPriv + 2 * sizeof(binPriv) && memcmp(buf, binPriv, sizeof(binPriv)) == 0);

    p = hex2bin(hexPub, buf, sizeof(buf));
    assert(p == hexPub + 2 * sizeof(binPub) && memcmp(buf, binPub, sizeof(binPub)) == 0);

    return 0;
}
0
2
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2