C++ char* to HEX conversion -


i want convert byte data (file body) hex in order print it. i've copied function conversion, not 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;     (int = 0; < 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 shift (4) , mask 0xf for? , how works? also, when i'am tried pass "1" argument func, returns 3100, supposed return 0100 because 1 1 in both dec or hex. wrong?

one digit in hexadecimal representation corresponds 4 bits in binary representation.

ch & 0xf0 masks out high 4 bits. >> 4 shifts them low bits.

0xab & 0xf0 -> 0xa0 0xa0 >> 4 -> 0xa 

ch & 0xf masks out low 4 bits.

0xab & 0xf -> 0xb 

the reason unexpected result character '1' 0x31 (49 in decimal) in ascii encoding.
you're looking character's numerical representation, not number represents.

you'll expected results if do

char data[] = {1}; 

Comments

Popular posts from this blog

Magento/PHP - Get phones on all members in a customer group -

php - Bypass Geo Redirect for specific directories -

php - .htaccess mod_rewrite for dynamic url which has domain names -