简体   繁体   中英

C++ char* to HEX conversion

I want to convert byte data (file body) to hex in order to print it. I've copied a function for conversion, but not exactly understand it.

#include "stdafx.h"
#include <iostream>
#include <Windows.h>
#include <string>

std::string byte_2_str(char* bytes, int size) {
    char const hex[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A',   'B','C','D','E','F'};
    std::string str;
    for (int i = 0; i < size; ++i) {
        const char ch = bytes[i];
        str.append(&hex[(ch  & 0xF0) >> 4], 1);
        str.append(&hex[ch & 0xF], 1);
    }

return str;

}

int _tmain(int argc, _TCHAR* argv[])
{

    char data[] = "1";
    std::string str = byte_2_str(data, sizeof(data));
    std::cout << str << std::endl;


    system("PAUSE");
    return 0;
}

What is that shift (4) and mask 0xF for? And how it works? Also, when i'am tried to pass "1" as argument to func, it returns 3100, but i supposed it will return 0100 because 1 is 1 in both dec or hex. Am i wrong?

One digit in the hexadecimal representation corresponds to four bits in the binary representation.

ch & 0xF0 masks out the high four bits. >> 4 shifts them into the low bits.

0xAB & 0xF0 -> 0xA0
0xA0 >> 4 -> 0xA

ch & 0xF masks out the low four bits.

0xAB & 0xF -> 0xB

The reason for your unexpected result is that the character '1' is 0x31 (49 in decimal) in the ASCII encoding.
You're looking up the character's numerical representation, not the number it represents.

You'll get the expected results if you do

char data[] = {1};

Side note:

Also, when i'am tried to pass "1" as argument to func, it returns 3100

This is correct. The function takes a char array, but operates on the array as raw data, not as if it was a set of characters. This is just because C does not have a "byte" type, and because the char type is guaranteed to be 8 bits, it's the most convenient type that can be used to represent bytes.

If you look in the ASCII table, '1' corresponds to 0x31. If you use the following, then you'll see the output you expect:

char[] data = {1};

As the others have said, you then get the 0x00 after it because your existing code is also including the NULL terminator.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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