admin管理员组文章数量:1332889
I'm running a server on Python which sends data to JavaScript. This server however can only send bytes. I'm needing the data to be in integer form. Is there a way to convert this in Javascript.
Here's the line of Code that's receiving the data. How can I transform evt.data from bytes to Integers. What I'm receiving from Python is the b' followed by the number. Example: b'120'
ws.onmessage = function (evt) {
var received_msg = evt.data;
Here is the line of code that is used to Send data from Python. It's UDP and unfortunately can only send bytes. I'm sending data from a python server to python client and then to a python websocket server. That python web socket server unfortunately can't send over the bytes converted to ints via the " int() " method.
sock.sendto(bytes(MESSAGE, "utf-8"), (ip_address, UDP_PORT))
What do I need to do? Thanks in Advance! :)
I'm running a server on Python which sends data to JavaScript. This server however can only send bytes. I'm needing the data to be in integer form. Is there a way to convert this in Javascript.
Here's the line of Code that's receiving the data. How can I transform evt.data from bytes to Integers. What I'm receiving from Python is the b' followed by the number. Example: b'120'
ws.onmessage = function (evt) {
var received_msg = evt.data;
Here is the line of code that is used to Send data from Python. It's UDP and unfortunately can only send bytes. I'm sending data from a python server to python client and then to a python websocket server. That python web socket server unfortunately can't send over the bytes converted to ints via the " int() " method.
sock.sendto(bytes(MESSAGE, "utf-8"), (ip_address, UDP_PORT))
What do I need to do? Thanks in Advance! :)
Share Improve this question asked Jun 18, 2020 at 3:03 divad99divad99 231 gold badge1 silver badge5 bronze badges 2-
Just to be clear in Javascript you are getting a string line
"b'120'"
? That doesn't seem correct as that's how python represents bytes as a string. – Mark Commented Jun 18, 2020 at 3:16 - 1 Yes! You are correct, I was pasing it through the "str()" method! @MarkMeyer – divad99 Commented Jun 18, 2020 at 4:26
2 Answers
Reset to default 3Javascript doesn't support 64 bits integers. That said this function should do the trick for 32 bit signed integers:
var byteArrayToInt = function(byteArray) {
var value = 0;
for (var i = byteArray.length - 1; i >= 0; i--) {
value = (value * 256) + byteArray[i];
}
return value;
};
I hope this helps
function binToInt(bin){
return parseInt(bin, 2);
}
console.log(binToInt("00101001")); //Outputs 41
本文标签: pythonHow do I convert Bytes to Integers in JavascriptStack Overflow
版权声明:本文标题:python - How do I convert Bytes to Integers in Javascript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742311608a2450981.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论