简体   繁体   English

如何在 Javascript 中将字节转换为整数?

[英]How do I convert Bytes to Integers in Javascript?

I'm running a server on Python which sends data to JavaScript.我在 Python 上运行一个服务器,它将数据发送到 JavaScript。 This server however can only send bytes.但是,此服务器只能发送字节。 I'm needing the data to be in integer form.我需要数据采用 integer 形式。 Is there a way to convert this in Javascript.有没有办法在 Javascript 中转换它。

Here's the line of Code that's receiving the data.这是接收数据的代码行。 How can I transform evt.data from bytes to Integers.如何将 evt.data 从字节转换为整数。 What I'm receiving from Python is the b' followed by the number.我从 Python 收到的是 b' 后跟数字。 Example: b'120'示例: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.这是用于从 Python 发送数据的代码行。 It's UDP and unfortunately can only send bytes.它是 UDP ,不幸的是只能发送字节。 I'm sending data from a python server to python client and then to a python websocket server.我将数据从 python 服务器发送到 python 客户端,然后发送到 python ZBF56D570E62CDB573C87B185262961 服务器。 That python web socket server unfortunately can't send over the bytes converted to ints via the " int() " method.不幸的是,python web 套接字服务器无法发送通过“int()”方法转换为整数的字节。

sock.sendto(bytes(MESSAGE, "utf-8"), (ip_address, UDP_PORT))

What do I need to do?我需要做什么? Thanks in Advance: :)提前致谢: :)

I hope this helps我希望这有帮助

 function binToInt(bin){ return parseInt(bin, 2); } console.log(binToInt("00101001")); //Outputs 41

Javascript doesn't support 64 bits integers. Javascript 不支持 64 位整数。 That said this function should do the trick for 32 bit signed integers:这就是说这个 function 应该对 32 位有符号整数起作用:

var byteArrayToInt = function(byteArray) {
    var value = 0;
    for (var i = byteArray.length - 1; i >= 0; i--) {
        value = (value * 256) + byteArray[i];
    }

    return value;
};

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

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