gpt4 book ai didi

c++ - 在 protobuf 中使用 int32 的原因

转载 作者:搜寻专家 更新时间:2023-10-31 00:27:30 25 4
gpt4 key购买 nike

在 gpb proto2 ( https://developers.google.com/protocol-buffers/docs/proto#scalar ) 标量类型的描述中,它说:

  • int32

    Uses variable-length encoding. Inefficient for encoding negative numbers – if your field is likely to have negative values, use sint32 instead.

  • sint32

    Uses variable-length encoding. Signed int value. These more efficiently encode negative numbers than regular int32s.

对于正值,sint32 是否与 int32 一样有效?

换句话说,有没有理由使用int32?

如果使用什么语言很重要,我只对 C++ 感兴趣。

最佳答案

https://developers.google.com/protocol-buffers/docs/encoding#signed-integers

带符号的 varint 是通过在正值和负值之间交替进行编码的。例如,

   value     int32    zigzag    sint32
(binary) (binary)
0 00000000 0 00000000
-1 11111111 1 00000001
11111111
11111111
11111111
00001111
1 00000001 2 00000010
-2 11111110 3 00000011
11111111
11111111
11111111
00001111
...
63 00111111 126 01111110
-64 11000000 127 01111111
11111111
11111111
11111111
00001111
64 01000000 128 10000000
00000001
...

平均而言,将正数编码为 sint 比编码为 int 需要多一位。

(展开并运行以下代码片段以进行现场演示。)

function encode_varint(number) {
if (!number) return [0];
var bytes = [];
while (number) {
var byte = number & 0x7F;
number >>>= 7;
if (number) byte |= 0x80;
bytes.push(byte);
}
return bytes;
}
function format_bytes(bytes) {
var output = '';
for (var i = 0; i < bytes.length; i++) {
if (i) output += ' ';
output += bytes[i].toString(2).padStart(8, '0');
}
return output;
}
var valueElem = document.getElementById('value');
var int32Elem = document.getElementById('int32');
var sint32Elem = document.getElementById('sint32');
function update() {
var value = parseInt(valueElem.value);
var int32 = encode_varint(value);
var sint32 = encode_varint(value << 1 ^ -(value < 0));
int32Elem.value = format_bytes(int32);
sint32Elem.value = format_bytes(sint32);
}
valueElem.addEventListener('change', update);
update();
#varint {
display: grid;
grid-template-columns: max-content auto;
grid-row-gap: 1ex;
grid-column-gap: 1ch;
}
#varint label {
text-align: right;
}
#varint input {
font-family: monospace;
}
<form id='varint' onsubmit='return false'>
<label for='value'>value</label>
<input id='value' type='number' value='0'>
<label for='int32'>int32</label>
<input id='int32' type='text' readonly>
<label for='sint32'>sint32</label>
<input id='sint32' type='text' readonly>
</form>

关于c++ - 在 protobuf 中使用 int32 的原因,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48821216/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com