scala_bytestring 发表于 2017-04-21 | 更新于 2019-05-07 | 评论数: | 阅读次数: scala bytestring上代码: 1234567891011121314151617object TestByteString extends App { implicit val byteOrder: ByteOrder = ByteOrder.BIG_ENDIAN val bsb = new ByteStringBuilder(); bsb.append(ByteString ( int2Bytes(2) )); val bs = bsb.result(); println(bs.iterator.getInt) def int2Bytes(value: Int): Array[Byte] = { Array(((value >> 24) & 0xFF).toByte, ((value >> 16) & 0xFF).toByte, ((value >> 8) & 0xFF).toByte, (value & 0xFF).toByte) }} 我们来看看ByteIterator的getInt方法: 12345678910111213def getInt(implicit byteOrder: ByteOrder): Int = {if (byteOrder == ByteOrder.BIG_ENDIAN) ((next() & 0xff) << 24 | (next() & 0xff) << 16 | (next() & 0xff) << 8 | (next() & 0xff) << 0)else if (byteOrder == ByteOrder.LITTLE_ENDIAN) ((next() & 0xff) << 0 | (next() & 0xff) << 8 | (next() & 0xff) << 16 | (next() & 0xff) << 24)else throw new IllegalArgumentException("Unknown byte order " + byteOrder)} 相当于遍历byte数组再左移再用或运算 欢迎关注我的公众号:沉迷Spring 本文作者: John | 微信公众号【沉迷Spring】 本文链接: http://johnwonder.github.io/2017/04/21/scala-bytestring/ 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!