How to make a 32-bit and 16-bit integers using 16-bit and 8-bit integers

You can use the following functions to merge 2 words (16-bit) or 4 bytes (8-bit) into a 32-bit integer. There is also a function which makes a word (16-bit) using two bytes (8-bit). I am using the in my Qt/C++ projects whenever I need them but with a slight change you can use them on your non-Qt projects too.

First function is qMakeU16 which merges two bytes:

quint16 qMakeU16(quint8 l, quint8 h)
{
	quint16 result;
	quint8* result_arr = (quint8*)& result;
	result_arr[0] = h;
	result_arr[1] = l;
	return result;
}

Next is qMakeU32 which can combine two words into an integer:

quint32 qMakeU32(quint16 l, quint16 h)
{
	quint32 result;
	quint16* result_arr = (quint16*)& result;
	result_arr[0] = h;
	result_arr[1] = l;
	return result;
}

And finally there is another form of qMakeU32 which merges 4 bytes into an integer:

quint32 qMakeU32(quint8 lowest, quint8 low, quint8 high, quint8 highest)
{
	quint32 result;
	quint8* result_arr = (quint8*)& result;
	result_arr[0] = highest;
	result_arr[1] = high;
	result_arr[2] = low;
	result_arr[3] = lowest;
	return result;
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.