gpt4 book ai didi

objective-c - 将字节转换为 UInt8 (Swift 3)

转载 作者:行者123 更新时间:2023-11-28 10:57:00 25 4
gpt4 key购买 nike

我有以下用 Objective-C 编写的代码:

int port1 = SERVER_DEVICE_PORT;
int port2 = SERVER_DEVICE_PORT>>8;

Byte port1Byte[1] = {port1};
Byte port2Byte[1] = {port2};

NSData *port1Data = [[NSData alloc]initWithBytes: port1Byte length: sizeof(port1Byte)];
NSData *port2Data = [[NSData alloc]initWithBytes: port2Byte length: sizeof(port2Byte)];

我已经像这样将它转换为 Swift 3:

let port1: Int = Int(SERVER_DEVICE_PORT)
let port2: Int = Int(SERVER_DEVICE_PORT) >> 8

let port1Bytes: [UInt8] = [UInt8(port1)]
let port2Bytes: [UInt8] = [UInt8(port2)]

let port1Data = NSData(bytes: port1Bytes, length: port1)
let port2Data = NSData(bytes: port2Bytes, length: port2)

但是,使用此代码我收到以下错误:

enter image description here

如何解决这个问题?

最佳答案

在 Swift 3 中从 32 位值中获取两个最低字节的最简单方法是

var SERVER_DEVICE_PORT : Int32 = 55056

let data = Data(buffer: UnsafeBufferPointer(start: &SERVER_DEVICE_PORT, count: 1))
// or let data = Data(bytes: &SERVER_DEVICE_PORT, count: 2)
let port1Data = data[0]
let port2Data = data[1]

print(port1Data, port2Data)

此结果 UInt8 值,以获取 Data 使用

let port1Data = Data([data[0]])
let port2Data = Data([data[1]])

如果 - 由于某种原因 - 32 位值是大端(最小地址中的最高有效字节),则 port1Data = data[3]port2Data = data[2].

关于objective-c - 将字节转换为 UInt8 (Swift 3),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42856306/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com