Modbus is a big-endian protocol.  The more significant byte of a 16-bit value is sent before the less significant byte

So, for bytes on the bus a UInt16 is sent like this:

Bits15:8 | Bits7:0

Converting the modbus 16 bit words

UInt32 conversion

UInt16[0] | UInt16[1]

UInt64 conversion

UInt16[0] | UInt16[1] | UInt16[2] | UInt16[3]

Float conversion

UInt16[0] | UInt16[1]

	//Converting big endian modbus registers to float on little endian windows (ModbusRegisterValues[0] was received first)
	array<Byte>^byteArray = gcnew array<Byte>(4);
	byteArray[3] = (Byte)(ModbusRegisterValues[0] >> 8);
	byteArray[2] = (Byte)(ModbusRegisterValues[0] & 0x00ff);
	byteArray[1] = (Byte)(ModbusRegisterValues[1] >> 8);
	byteArray[0] = (Byte)(ModbusRegisterValues[1] & 0x00ff);
	float my_float = BitConverter::ToSingle(byteArray, 0);

	//Converting float on little endian windows to big endian modbus registers (ModbusRegisterValues[0] will be sent first)
	ModbusRegisterValues = gcnew array <UInt16>(2);
	array<Byte>^byteArray = BitConverter::GetBytes(my_float_value);
	ModbusRegisterValues[0] = ((UInt16)byteArray[3] << 8) | ((UInt16)byteArray[2]);		//Converting float on little endian windows to big endian modbus registers
	ModbusRegisterValues[1] = ((UInt16)byteArray[1] << 8) | ((UInt16)byteArray[0]);
char conversion

	//RegisterValues[] is UInt16 array read over modbus
	array<Byte> ^NameArray = gcnew array<Byte>(10);
	NameArray[0] = (Byte)(RegisterValues[0] >> 8);
	NameArray[1] = (Byte)(RegisterValues[0] & 0x00ff);
	NameArray[2] = (Byte)(RegisterValues[1] >> 8);
	NameArray[3] = (Byte)(RegisterValues[1] & 0x00ff);
	NameArray[4] = (Byte)(RegisterValues[2] >> 8);
	NameArray[5] = (Byte)(RegisterValues[2] & 0x00ff);
	NameArray[6] = (Byte)(RegisterValues[3] >> 8);
	NameArray[7] = (Byte)(RegisterValues[3] & 0x00ff);
	NameArray[8] = (Byte)(RegisterValues[4] >> 8);
	NameArray[9] = (Byte)(RegisterValues[4] & 0x00ff);
	sTemp = System::Text::Encoding::UTF8->GetString(NameArray);
	sTemp = sTemp->Replace("\0", "");




We benefit hugely from resources on the web so we decided we should try and give back some of our knowledge and resources to the community by opening up many of our company’s internal notes and libraries through mini sites like this. We hope you find the site helpful.
Please feel free to comment if you can add help to this page or point out issues and solutions you have found, but please note that we do not provide support on this site. If you need help with a problem please use one of the many online forums.


Your email address will not be published.