简体   繁体   English

有没有办法将任何数字编码为一系列 8 位数字,包括终止字符?

[英]Is there a way to encode any number into a series of 8-bit numbers, including a terminating character?

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...).所以我想编码小到 0 和大到非常高的数字(32 位、64 位、其他 8 位倍数......)。 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.简单的方法是只使用计算机体系结构对“字”大小或其他大小的内置支持,因此 32 位或 64 位是常见情况,因此整数仅限于该大小。 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.但是我想做一个理论上的事情,看看是否有一种方法可以使用 8 位数字序列对任意大的数字进行编码。

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

...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). ...其中n是数字, b是任意字节(此图与我所说的不太准确n在序列中会相当少,而b会相对大得多)。 And the thing is, the n is the number of bytes b in front of it .问题是, n是它前面的字节数b So this way you can do this:因此,您可以通过这种方式执行以下操作:

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

The question is two parts:问题分为两部分:

  1. How do you compute the number out of a sequence of 8-bit integers?如何从 8 位整数序列中计算出数字?
  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-first VLQ could be decoded into a BigInt like this: MSB-first VLQ 可以像这样解码成 BigInt:

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.这实际上是数据中下一件事的位置。

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

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