简体   繁体   中英

Convert 16 bits to 4 char ( in Hexadecimal)

I want to convert 16 bit to 4 characters which are in Hexadecimal character. For example, a 16 bit, 1101 1010 1101 0001 in hexadecimal is DAD1 and in decimal is 56017. Now I want to convert this 16 bit into DAD1 as characters so that I can use the character to write into a text file.

My coding part, my variable "CRC" is my result from CRC checksum. Now I want to convert 16 bit "CRC" into 4 characters which are DAD1 (capital letters).

cout << hex << CRC<<endl;
char lo = CRC & 0xFF;
char hi = CRC >> 8;
cout << hi << endl;
cout << lo;

*******Result********

dad1

Try this:

#include <iostream>
#include <bitset>
#include <string>
int main()
{
    int i = 56017;
    std::cout <<hex <<i << std::endl;
    std::bitset<16> bin = i;
    std::string str = bin.to_string();
    std::bitset<8> hi(str.substr(0, 8));
    std::bitset<8> lo(str.substr(8, 8));
    std::cout << bin << std::endl;
    std::cout << hi << " " << hi.to_ullong() << std::endl;
    std::cout << lo << " " << lo.to_ullong() << std::endl;
}

OR you can also do

std::cout <<hex << (CRC & 0xFF)<< std::endl;
std::cout << hex << (CRC >> 8) << std::endl;

Output:

在此处输入图片说明

Try This :

#include <iostream>
#include <bitset>
#include <limits>

int main()
{
    int i = 56017;
    std::bitset<std::numeric_limits<unsigned long long>::digits> b(i); 
    std::cout<< std::hex << b.to_ullong();    
}

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