简体   繁体   English

将一串Java float解析为python int

[英]Parse a string of Java float to python int

I have sockets sending data in string format between java and python. 我有套接字在java和python之间以字符串格式发送数据。 The python client receives floating point numbers in strings as eg data_in = "[F@5cf0ac6e" , and then attempts to convert them to integers with value = int(float(data_in[1:])) . python客户端接收字符串中的浮点数,例如data_in = "[F@5cf0ac6e" ,然后尝试将其转换为value = int(float(data_in[1:]))整数。 However python returns the error ValueError: could not convert string to float: F@5cf0ac6e . 但是python返回错误ValueError: could not convert string to float: F@5cf0ac6e How can get the java float values to integers in python? 如何在python中将Java float值转换为整数? Thanks! 谢谢!

If the first three characters of data_in are not relevant to the string of hex digits, your slice should be data_in[3:] . 如果data_in的前三个字符与十六进制字符串无关,则您的分片应为data_in[3:] This will ignore the [F@ characters, and just convert 5cf0ac6e . 这将忽略[F@字符,而只转换5cf0ac6e

However, the call to float() is not necessary. 但是,不需要调用float() Instead, use: 而是使用:

value = int(data_in[3:], 16)

as any floating point information is lost anyway with the conversion to an integer. 因为任何浮点信息都会随着转换为整数而丢失。 The 16 parameter to int() is necessary because you're converting from base 16 (hexadecimal). int()16参数是必需的,因为您要从基数16(十六进制)转换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM