# Confusion with Bitwise operators for Modbus

I am trying to understand what exactly what this function is doing.
This is a code for Modbus communication.
I recognize that the user is trying to write to several holding registers ie
modbusTCPClient.wrtie(16). The 16 being a function code for write to multiple registers.
anyways if someone could help me decifer the operators on the
modbusTCPClient.write( dataLen >> 8 );
modbusTCPClient.write( dataLen & 0xFF );
modbusTCPClient.write( dataLen * 2 );
for ( byte i = 0; i < dataLen; i++ ) {
modbusTCPClient.write( data[i] >> 8 );
modbusTCPClient.write( data[i] & 0xFF );

that would be great.
the function is called in the code as

uint16_t data[5];
writeMulti(2,0x40000,data,5)

``````void writeMulti( uint8_t id, uint8_t address, uint16_t *data, uint8_t dataLen ) {
modbusTCPClient.write( id );
modbusTCPClient.write( 16 );
modbusTCPClient.write( dataLen >> 8 );
modbusTCPClient.write( dataLen & 0xFF );
modbusTCPClient.write( dataLen * 2 );
for ( byte i = 0; i < dataLen; i++ ) {
modbusTCPClient.write( data[i] >> 8 );
modbusTCPClient.write( data[i] & 0xFF );
}
}type or paste code here
``````

It makes no sense, because `address` and `dataLen` are of type `uint8_t`..

You should know all of them.

Right. Im just not sure if Im calculating right.
If im
modbusTCPClient would be
modbusTCPClient(10011100)
or
modbusTCPClient(156)???

Im just not sure if Im doing something wrong or if this is just some Tom foolery.
Im calculating

modbusTCPClient.write(156);
modbusTCPClient.write(64);
modbusTCPClient.write(0);
modbusTCPClient.write(5);
modbusTCPClient.write(10);

Im assuming these numbers are correct since the guy who wrote this is pretty talented coder.
That is unless my math is wrong.

0x40000 is 0b‭1000000000000000000‬ in binary, that is 19 bits

`address` is of type `uint8_t`, so it can store only 8 bits (one byte), so it will keep only the first (right-most) 8 bits of 0x40000, so it will be 0

`0 >> 8 = 0` and `0 & 0xFF = 0`

This function is incorrect

I understand how you got 156 and 64, you are confusing 0x40000 with 40000, they are not the same! But 40000 is also too big for a byte

Alrighty.
well thanks for the quick response.
perhaps its 40000 in base 10 .That would be 16 bit or one word.
And perhaps this is just a "Shifty" way of taking the lower byte of a word
and doing some arithmetic.???

Change the function to

`void writeMulti( uint8_t id, uint16_t address, uint16_t *data, uint16_t dataLen )`

Also change `for ( byte i` to `for ( uint16_t i`

Call it with `writeMulti(2,40000,data,5)`

It should give the expected result

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.