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: