I start working with HART (Highway Addressable Remote Transducer) Protocol and I found something, let's say different and I try to understand it, more precisely the uint24. I understand that this structure uses an UInt32 internally for storage and most other common expected integer functionality, so using a 24-bit integer will not save memory. But my question is how can I convert an UInt32 to this specific type, I found these lines of code in Javascript but I don't know what is the purpose of those left shifting.
var getUint24 = function(bytes)
{
return (DataView(bytes.buffer).getUint16(0) << 8) + DataView(bytes.buffer).getUint8(0 + 2);
}
Also, I found this function that convert a number to 4 bytes. I also don't know what is the purpose o these shifting, but maybe if I understand these I can create my own version of the function that convert a simple number ex: 4 to his uint24 version.
/**
*
* @function ToBytesInt32 "Convert number to 4 bytes (eg: ToBytesInt32(2) returns 00 00 00 02"
* @param {number} num The input value
* @return {byte array}
*/
function ToBytesInt32BigEndian(num) {
if (isNaN(num)) {
throw "ToBytesInt32 received Nan! Called from: " +
testUtils.StrReplace.caller.toString().split('\n')[0];
}
arr = [
(num & 0xff000000) >> 24,
(num & 0x00ff0000) >> 16,
(num & 0x0000ff00) >> 8,
(num & 0x000000ff)
];
return arr;
}
If anyone can help me to understand the pourpose of those shifting I would apreciate it, also the C/C++ version is very welcomed.