我有一个uint64
(在C中是一个unsigned long long
),我想用一个字节数组来转换它。
,我现在就是这样做的(用Nim代码):
Value
是类型胡枝子,因为unsigned long long
Byte
是unsigned char
,unsigned char
CD
是Byte
s的数组
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)))
--我就是这样把它读回来的--(从数组中的一个特定位置开始获取一个uint64
:IP
)
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])
有没有更有效的方法?我这样做是在浪费表演吗?
发布于 2020-01-04 09:42:29
有一种更有效的方法。我不确定它是否安全,它不依赖于特定的机器和/或体系结构。
不管怎么说。您可以使用cast
:https://nim-lang.org/docs/manual.html#statements-and-expressions-type-casts来完成它。
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)
https://stackoverflow.com/questions/59405939
复制相似问题