登录
首页 >  Golang >  Go问答

将函数从 GO 转换为 Javascript:由偏移量和长度组成的范围超出范围

来源:stackoverflow

时间:2024-04-01 12:18:34 409浏览 收藏

学习Golang要努力,但是不要急!今天的这篇文章《将函数从 GO 转换为 Javascript:由偏移量和长度组成的范围超出范围》将会介绍到等等知识点,如果你想深入学习Golang,可以关注我!我会持续更新相关文章的,希望对大家都能有所帮助!

问题内容

我正在尝试将函数从 go 翻译为 javascript(我对 go 几乎一无所知)。

这是原来的函数

func preparemessage(data []byte) []byte {
    // compute crc before modifying the message.
    crc := crccompute(data)
    // add the two crc16 bytes before replacing control characters.
    data = append(data, byte(crc&0xff))
    data = append(data, byte(crc>>8))

    tmp := []byte{0x7e} // flag start.

    // copy the message over, escaping 0x7e (flag byte) and 0x7d (control-escape).
    for i := 0; i < len(data); i++ {
        mv := data[i]
        if (mv == 0x7e) || (mv == 0x7d) {
            mv = mv ^ 0x20
            tmp = append(tmp, 0x7d)
        }
        tmp = append(tmp, mv)
    }

    tmp = append(tmp, 0x7e) // flag end.

    return tmp
}

这是我在 javascript 中的尝试

var _appendBuffer = function (buffer1, buffer2) {
    var tmp = new Uint8Array(buffer1.byteLength + buffer2.byteLength);
    tmp.set(new Uint8Array(buffer1), 0);
    tmp.set(new Uint8Array(buffer2), buffer1.byteLength);
    return tmp.buffer;
  };

 function prepareMessage(data) {
    // Compute CRC before modifying the message.
    var crc = crcCompute(data)
    // Add the two CRC16 bytes before replacing control characters.
    data = data + (crc & 0xFF);
    data = data + (crc >> 8);

    var tmp = new ArrayBuffer(1000000000);
    tmp[0] = [0x7E]; // Flag start.

    // Copy the message over, escaping 0x7E (Flag Byte) and 0x7D (Control-Escape).
    for (var i = 0; i < data.length; i++) {
      var mv = data[i]
      if ((mv == 0x7E) || (mv == 0x7D)) {
        mv = mv ^ 0x20;
        tmp = _appendBuffer(tmp, [0x7D]);
      }
      tmp = _appendBuffer(tmp, mv);
    }

    tmp = _appendBuffer(tmp, [0x7E]); // Flag end.
    return tmp;
  }

在preparemessage函数中出现此错误 rangeerror:由偏移量和长度组成的范围为bounds 在线 tmp = _appendbuffer(tmp, mv);

我知道缓冲区大小有问题,但我不知道如何修复它。

谢谢 莱昂


正确答案


tmp := []byte{0x7E} // 标志 start. 被声明并初始化为一个只有 1 项的数组。它已经满了,请尝试使用 make() 函数制作一个容量更大的切片。

这是一篇很好的文章,有更多细节。 https://www.godesignpatterns.com/2014/05/arrays-vs-slices.html

好了,本文到此结束,带大家了解了《将函数从 GO 转换为 Javascript:由偏移量和长度组成的范围超出范围》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>