Why does `encoding/binary` behave so weird?

xuanbao · · 407 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>I have lets say the number <code>5000</code> when i encode it into bytes it should be <code>[]byte{136,19}</code> which comes from <code>[]byte{5e3&amp;0xff,5e3&gt;&gt;8}</code>.</p> <p>But golang results <code>[]byte{136,39}</code>. WTH is 39 i have no clue?</p> <hr/>**评论:**<br/><br/>dogestopmewow: <pre><p>Can you elaborate on what you&#39;re doing exactly, as I&#39;m unable to reproduce your problem?</p> <p>Here is an example where everything is working as expected: <a href="https://play.golang.org/p/6HnTt7SuYd_G" rel="nofollow">https://play.golang.org/p/6HnTt7SuYd_G</a></p></pre>korthaj: <pre><p>Perhaps you used one of the variable-length encoding functions by mistake? I know I have...</p></pre>TheMerovius: <pre><p>You are using <a href="https://godoc.org/encoding/binary#PutUvarint" rel="nofollow">PutUvarint</a>, giving you <a href="https://play.golang.org/p/NHAYfLvL7gx" rel="nofollow">this result</a>, which is expected, as that&#39;s the <a href="https://developers.google.com/protocol-buffers/docs/encoding#varints" rel="nofollow">varint-encoding</a> of 5000.</p> <p>Use <code>binary.LittleEndian.PutUint64</code> or <code>binary.Write</code>, as <a href="/u/dogestopmewow" rel="nofollow">/u/dogestopmewow</a> demonstrates to get fixed-width little-endian encoding.</p></pre>

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

407 次点击  
加入收藏 微博
0 回复
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传