# How could C transfer to Python

**URL:** <https://forums.digi.com/t/how-could-c-transfer-to-python/2856>\
**Category:** Python\
**Created:** [November 26, 2012, 6:41am UTC](https://forums.digi.com/t/how-could-c-transfer-to-python/2856 "2012-11-26T06:41:15Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![v730825](https://avatars.discourse-cdn.com/v4/letter/v/f04885/32.png) [@v730825](https://forums.digi.com/u/v730825)\
**Post date:** [November 26, 2012, 6:41am UTC](https://forums.digi.com/t/how-could-c-transfer-to-python/2856/1 "2012-11-26T06:41:15Z")

</div>

Python Language:  
…  
mbrtu = “”  
mbrtu += chr(1)  
mbrtu += chr(3)  
mbrtu += chr(1)  
mbrtu += chr(0)  
mbrtu += chr(0)  
mbrtu += chr(2)  
crc = calcString( mbrtu, INITIAL\_MODBUS)  
print hex(crc) #output 0xf7c5  
mbrtu += chr(crc & 0xFF) + chr((crc \>\> 8) & 0xFF)

sd.sendto(mbrtu, 0, DESTINATION)  
payload, src\_addr = sd.recvfrom(100)

#error here  
Data = (int(payload[3]\<\<8)) + (int(payload[4]))  
#TypeError: unsupported operand type(s) for \<\<: ‘str’ and ‘int’

## #pValue = (float(Data))/power(10,1) #print “received:”, pValue

C Language: it works  
…  
cmdBuf[0] = 1 ;  
cmdBuf[1] = 3 ;  
cmdBuf[2] = 1 ;  
cmdBuf[3] = 0 ;  
cmdBuf[4] = 0 ;  
cmdBuf[5] = 2 ;  
CRC = CRC16\_T(cmdBuf,Len);  
cmdBuf[6] = 0xFF & CRC ;  
cmdBuf[7] = 0xFF & (CRC\>\>8) ;  
write(fd,cmdBuf,Len+2);  
ret=read(fd,rbuf,100);  
Data = ((int)rbuf[3]\<\<8) + ((int) rbuf[4]);

How could I transfer C to Python language?  
Sorry,it is my first time use Python language.

---

<div class="post-metadata">

**Author:** ![mcarver](https://avatars.discourse-cdn.com/v4/letter/m/87869e/32.png) [@mcarver](https://forums.digi.com/u/mcarver)\
**Post date:** [November 26, 2012, 3:19pm UTC](https://forums.digi.com/t/how-could-c-transfer-to-python/2856/2 "2012-11-26T15:19:02Z")

</div>

I don’t know much python, but I think the \<\< operator takes precedence over casting (if python supports casting?) so maybe it should read:

Data = ((int(payload[3]))\<\<8) + (int(payload[4]))

---

<div class="post-metadata">

**Author:** ![lynnl](https://avatars.discourse-cdn.com/v4/letter/l/22d042/32.png) [@lynnl](https://forums.digi.com/u/lynnl)\
**Post date:** [November 26, 2012, 5:53pm UTC](https://forums.digi.com/t/how-could-c-transfer-to-python/2856/3 "2012-11-26T17:53:28Z")

</div>

mcarver’s answer looks almost correct. payload[3]\<\<8 will fail because you cannot shift Python characters - unlike in C where a char == byte == int, in Python it is a string of length=1.

However, I think even int(‘A’) will fail because ‘A’ isn’t a digit. Doing "Data = int(‘1’)’ sets Data to 1, not the ascii-bit equivalent of 0x31.

The normal Python way is this:  
Data = (ord(payload[3])\<\<8) + ord(payload[4])

Or some people use the Python ‘struct’ module, but that is overkill for a simple digit.
