PDA

View Full Version : How to convert binary data to hexadecimal data

yellowmat
7th March 2006, 17:00
Here I am again :) but with a different problem.

I have an object that reads data from the serial port. This is binary data that match some key presses. Each key press has a hexadecimal value that I must extract from the binary data.

My questions are the following :
1. Is it possible to convert binary data to hexadecimal data ?
2. If it is possible, how could I make the convertion between binary to hexadecimal ?

KMAPSRULE
7th March 2006, 17:38
If you are just trying to display Hex Codes you can use the QString::number() Function.

int myBase = 16;
QString str = QString::number( my_binary_value, myBase);

where my_binary_value is one of:

int
uint
Q_LLONG
Q_ULLONG
long
ulong
double

yellowmat
8th March 2006, 10:28
I used QString::toLong but the conversion always failed.

I use your code and it is ok.

thanks

wysota
8th March 2006, 12:20
Please note, that you can't really distinguish between "binary" and "hexadecimal" data (and "octal" too). All of these have the same representation. Every modern computer keeps its data in all three of those formats at once, so there is no "conversion" from binary to hexadecimal or whatsoever -- there is only a matter of displaying data in binary, octal or hexadecimal form.

For example, if I want to display a decimal number 100:

hexadecimal: (100d = 6*16d + 4d) => 64h (0x64)
octal: (100d = 1*64d + 4*8d + 4d) => 144o (0144)
binary: (100d = 1*64d + 1*32d + 1*4d) => 1100100b

All data is stored as a series of bits, with each bit representing a single binary digit. But also three bits form an octal digit and on the same time four bits form a hexadecimal digit. So it is only a matter of taking an appropriate number of bits from the binary encoded values: 1100100 = (001) (100) (100) = (0110) (0100)

KMAPSRULE
8th March 2006, 17:17
For those less mathematically inclined a code example of what wysota is saying:

#include <iostream>

int main(int argc, char *argv[])
{

int myBase10 = 15; //15 in decimal
int myBase8 = 017; //15 in octal
int myBase16 = 0x000F; //15 in hex (leading zeros just to remind me that this is a 32 bit representation...its a personal preference 0xF would do )

if( (myBase10 == myBase16) && (myBase10 == myBase8) && (myBase16 == myBase8) )
{
std::cout << "They are all Equal, Under the Hood the Computer sees each of these as a 32 bit(because typed as int) base2 Number" << std::endl;
std::cout << "eg.( 0000000000001111 )(little endian order listed)" << std::endl;
std::cout << "It is the language and Compiler that give you the convenience of thinking in hex/octal/decimal..." << std::endl;

}//end if all ints are equal

return( 0 );
}//end main