Swift 或 Objective C 中 java ByteBuffer 的等价物是什么?

我需要在java中以相同的方式创建一些随机数据。像下面这个片段。


ByteBuffer bb = ByteBuffer.allocate(16);

 bb.putDouble(0, Math.random());

 bb.putDouble(8, Math.random());

 String input = Hex.encodeHexString(bb.array());


如何在 iOS (Swift 或 Objective-C) 中做同样的事情,iOS 中 ByteBuffer 的等价物是什么?


潇湘沐
浏览 174回答 1
1回答

森林海

我相信你要找的对象是Data. 它是一个可以表示任何数据并保存原始字节缓冲区的对象。对于您的特定情况,您需要将 double 值数组转换为数据,可以这样做:let data: Data = doubleArray.withUnsafeBufferPointer { Data(buffer: $0) }现在要从中获取十六进制字符串,Data我建议您参考其他一些帖子。添加此答案代码,您应该能够通过执行以下操作来构建您的十六进制字符串let hexString = data.hexEncodedString()所以把它放在一起,你会这样做:extension Data {&nbsp; &nbsp; struct HexEncodingOptions: OptionSet {&nbsp; &nbsp; &nbsp; &nbsp; let rawValue: Int&nbsp; &nbsp; &nbsp; &nbsp; static let upperCase = HexEncodingOptions(rawValue: 1 << 0)&nbsp; &nbsp; }&nbsp; &nbsp; func hexEncodedString(options: HexEncodingOptions = []) -> String {&nbsp; &nbsp; &nbsp; &nbsp; let format = options.contains(.upperCase) ? "%02hhX" : "%02hhx"&nbsp; &nbsp; &nbsp; &nbsp; return map { String(format: format, $0) }.joined()&nbsp; &nbsp; }}func generateRandomDoubleBufferHexString(count: Int, randomParameters: (min: Double, max: Double, percision: Int) = (0.0, 1.0, 100000)) -> String {&nbsp; &nbsp; func generateRandomDouble(min: Double = 0.0, max: Double = 1.0, percision: Int = 100000) -> Double {&nbsp; &nbsp; &nbsp; &nbsp; let scale: Double = Double(Int(arc4random())%percision)/Double(percision)&nbsp; &nbsp; &nbsp; &nbsp; return min + (max-min)*scale&nbsp; &nbsp; }&nbsp; &nbsp; var doubleArray: [Double] = [Double]() // Create empty array&nbsp; &nbsp; // Fill array with random values&nbsp; &nbsp; for _ in 0..<count {&nbsp; &nbsp; &nbsp; &nbsp; doubleArray.append(generateRandomDouble(min: randomParameters.min, max: randomParameters.max, percision: randomParameters.percision))&nbsp; &nbsp; }&nbsp; &nbsp; // Convert to data:&nbsp; &nbsp; let data: Data = doubleArray.withUnsafeBufferPointer { Data(buffer: $0) }&nbsp; &nbsp; // Convert to hex string&nbsp; &nbsp; return data.hexEncodedString()}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java