有没有一种方法可以将任何数字编码为一系列8位数字,包括一个终止字符? [英] Is there a way to encode any number into a series of 8-bit numbers, including a terminating character?

查看:119
本文介绍了有没有一种方法可以将任何数字编码为一系列8位数字,包括一个终止字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我想编码小到0到非常高的数字(32位,64位,其他8位倍数...).一种简单的方法是仅使用计算机体系结构对字"大小或其他大小的内置支持,因此常见的情况是像32位或64位,因此将整数限制为该大小.但是我想做一个理论上的事情,看看是否有一种方法可以使用8位数字序列对任意大数字进行编码.

So I would like to encode numbers as small as 0 and as high as very high (32-bit, 64-bit, other 8-bit multiples...). The simple approach is to just use the computer architecture's built-in support for "word" size or whatever, so like 32-bit or 64-bit are the common cases, so integers limited to that size. But I would like to do a theoretical thing and see if there is a way to encode arbitrarily large numbers using a sequence of 8-bit numbers.

但是,请注意,我想知道何时到达字节流中的数字的末尾.因此,您可能会有以下字节流:

But then as a caveat, I want to know when we've reached the end of a number in a stream of bytes. So you might have this stream of bytes:

nbbbbbbbbbbbbnnnnnbbbnnbnnnnnnnnnbbbbbbbnnbnnbb

...其中n是数字,而b是任意字节(此绘图与我所说的不太吻合.n顺序上很少,而b会相对更大).问题是, n是它前面的字节数b .因此,您可以这样做:

...where n is the number and b is an arbitrary byte (this drawing isn't quite accurate to what I'm saying. n would be fairly few in sequence, while b would be relatively much larger). And the thing is, the n is the number of bytes b in front of it. So this way you can do this:

  1. 通过某种方式组合n的序列来读取数字.
  2. 跳过该字节数以到达下一个n序列.
  3. 重复.
  1. Read the number by combining the sequences of n somehow.
  2. Skip that number of bytes to reach the next sequence of n.
  3. Repeat.

问题有两个部分:

  1. 如何计算8位整数序列中的数字?
  2. 这样,您也知道何时到达数字"编码的结尾,现在位于任意字节"编码部分.到达数字编码的结尾时,您需要某种方式保留一些键号或位来进行标记,但是我还没有弄清楚.
  1. How do you compute the number out of a sequence of 8-bit integers?
  2. Such that, you also know when you've reached the end of the "number" encoding and are now at the "arbitrary byte" encoding section. Somehow you need to reserve some key numbers or bits to flag when you've reached the end of a number encoding, but I haven't figured this out.

有什么想法可以做到这一点吗?

Any ideas how to accomplish this?

推荐答案

MSB优先VLQ可以这样解码为BigInt:

MSB-first VLQ could be decoded into a BigInt like this:

function decode(bytes, index) {
    index |= 0;
    var value = 0n;
    var t;
    do {
        t = bytes[index++];
        value = (value << 7n) | BigInt(t & 0x7F);
    } while (t >= 0x80);
    return { value: value, index: index };
}

还返回结束"位置.确实是数据中下一件事的位置.

The "end" position is also returned. It's really the position of the next thing in the data.

这篇关于有没有一种方法可以将任何数字编码为一系列8位数字,包括一个终止字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆