【发布时间】:2023-03-21 04:29:02
【问题描述】:
这是旧的 Objective C 代码(令牌是 NSData):
const unsigned *tokenBytes = [credentials.token bytes];
NSString *hexToken = [NSString stringWithFormat:@"%08x%08x%08x%08x%08x%08x%08x%08x",
ntohl(tokenBytes[0]), ntohl(tokenBytes[1]), ntohl(tokenBytes[2]),
ntohl(tokenBytes[3]), ntohl(tokenBytes[4]), ntohl(tokenBytes[5]),
ntohl(tokenBytes[6]), ntohl(tokenBytes[7])];
这是我将它转换为 Swift 的方法:
let tokenBytes = credentials.token.withUnsafeBytes { (bytes: UnsafePointer<[UInt]>) -> [UInt] in
return bytes[0] // Crash here
}
let hexToken = String(format: "%08x%08x%08x%08x%08x%08x%08x%08x",
UInt(bigEndian: tokenBytes[0]), UInt(bigEndian: tokenBytes[1]),
UInt(bigEndian: tokenBytes[2]), UInt(bigEndian: tokenBytes[3]),
UInt(bigEndian: tokenBytes[4]), UInt(bigEndian: tokenBytes[5]),
UInt(bigEndian: tokenBytes[6]), UInt(bigEndian: tokenBytes[7])
)
有谁知道我做错了什么?据我所知,我正确地从bytes 转换为withUnsafeBytes,但似乎我错了。
【问题讨论】:
-
您登录
bytes看看里面有什么?print(bytes[0])- 我敢打赌它未定义 -
只是一堆数字,不确定是否有帮助。老实说,我在这里已经脱离了我的联盟,对字节/低级别的东西没有太多经验。编辑:刚刚看到你想让我打印下标。我会这样做并回复你。
-
粘贴
print(bytes)和print(bytes[0])的输出 -
0x00000002815f6cb0 为前者,字节崩溃[0]
-
是的,所以我认为您不能将
0x00000002815f6cb0视为一个数组,它是一个UnsafePointer,我对 swift 不是很熟悉,但它指向内存中的一个位置。
标签: objective-c swift pointers