首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >将无符号64位整数拆分为字节的最佳方法

将无符号64位整数拆分为字节的最佳方法
EN

Stack Overflow用户
提问于 2019-12-19 08:37:21
回答 1查看 662关注 0票数 0

我有一个uint64 (在C中是一个unsigned long long ),我想用一个字节数组来转换它。

,我现在就是这样做的(用Nim代码):

  • Value是类型胡枝子,因为unsigned long long
  • Byteunsigned charunsigned char
  • CDBytes

的数组

代码语言:javascript
运行
复制
        proc writeValue(v:Value) =
            CD.add(Byte(v shr 56))
            CD.add(Byte(v and Value(0x00ff000000000000)))
            CD.add(Byte(v and Value(0x0000ff0000000000)))
            CD.add(Byte(v and Value(0x000000ff00000000)))
            CD.add(Byte(v and Value(0x00000000ff000000)))
            CD.add(Byte(v and Value(0x0000000000ff0000)))
            CD.add(Byte(v and Value(0x000000000000ff00)))
            CD.add(Byte(v and Value(0x00000000000000ff)))

--我就是这样把它读回来的--(从数组中的一个特定位置开始获取一个uint64IP)

代码语言:javascript
运行
复制
template readValue():Value =
    inc(IP,8); (Value(CD[IP-8]) shl 56) or (Value(CD[IP-7]) shl 48) or (Value(CD[IP-6]) shl 40) or (Value(CD[IP-5]) shl 32) or (Value(CD[IP-4]) shl 24) or (Value(CD[IP-3]) shl 16) or (Value(CD[IP-2]) shl 8) or Value(CD[IP-1])

有没有更有效的方法?我这样做是在浪费表演吗?

EN

回答 1

Stack Overflow用户

发布于 2020-01-04 09:42:29

有一种更有效的方法。我不确定它是否安全,它不依赖于特定的机器和/或体系结构。

不管怎么说。您可以使用casthttps://nim-lang.org/docs/manual.html#statements-and-expressions-type-casts来完成它。

代码语言:javascript
运行
复制
type Value = uint64
type Byte = uint8
type ValueBytes = array[0..7, Byte]

proc toBytes(v: Value): ValueBytes =
  result = cast[ValueBytes](v)

proc toValue(bytes: ValueBytes): Value =
  result = cast[Value](bytes)

proc toBytesManual(v: Value): ValueBytes =
  result[0] = Byte((v shr 0) and Value(0xff))
  result[1] = Byte((v shr 8) and Value(0xff))
  result[2] = Byte((v shr 16) and Value(0xff))
  result[3] = Byte((v shr 24) and Value(0xff))
  result[4] = Byte((v shr 32) and Value(0xff))
  result[5] = Byte((v shr 40) and Value(0xff))
  result[6] = Byte((v shr 48) and Value(0xff))
  result[7] = Byte((v shr 56) and Value(0xff))

proc toValueManual(bytes: ValueBytes): Value =
  result += Value(bytes[0]) shl 0
  result += Value(bytes[1]) shl 8
  result += Value(bytes[2]) shl 16
  result += Value(bytes[3]) shl 24
  result += Value(bytes[4]) shl 32
  result += Value(bytes[5]) shl 40
  result += Value(bytes[6]) shl 48
  result += Value(bytes[7]) shl 56

let value = 123456789'u64
let bytes = [21'u8, 205'u8, 91'u8, 7'u8, 0'u8, 0'u8, 0'u8, 0'u8]

assert toBytes(value) == bytes
assert toBytesManual(value) == toBytes(value)
assert toValue(bytes) == value
assert toValue(bytes) == toValueManual(bytes)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59405939

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档