Equivalent of readUIntLE in Golang?

blov · · 628 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>I need to read a byte at the position X of length Y.</p> <p>To do this in Node.js, I&#39;m using the Buffer class and the readUIntLE function. For example: readUIntLE(position, 3).</p> <p>What is the equivalent of the above mentioned process in Golang if the input is a byte array?</p> <p>The readUIntLE function reads X bytes at position Y in the buffer and converts those bytes to an unsigned 24-bit integer (little endian).</p> <p>Thanks!</p> <hr/>**评论:**<br/><br/>Ainar-G: <pre><p><a href="http://golang.org/pkg/encoding/binary/">http://golang.org/pkg/encoding/binary/</a> might be what you&#39;re looking for.</p></pre>pdq: <pre><p>Yep.</p> <p>Here&#39;s an example I wrote using BigEndian and LittleEndian:</p> <p><a href="http://play.golang.org/p/1pdEjpKo-H" rel="nofollow">http://play.golang.org/p/1pdEjpKo-H</a></p> <p>OP can tweak it for your 24-bit case -- use Uint32() and then shift right 8 bits.</p></pre>win32re: <pre><p>Thanks, this is the final code. s.Pos is the reading position and s.Data is the byte slice I&#39;m reading from.</p> <pre><code>func (s *Stream) ReadUIntLE(count int) uint64 { var n uint64 buff := s.Data[s.Pos : s.Pos + count] s.Pos += 3 for i, b := range buff { n += uint64(b) &lt;&lt; uint(8 * i) } return n } func ByteSwap(value uint64) uint32 { buf := make([]byte, 8) binary.LittleEndian.PutUint64(buf, value) return binary.BigEndian.Uint32(buf) &gt;&gt; 8 } </code></pre></pre>

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

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