2

I need to create some random data in the same way in java. Like this following snippet.

ByteBuffer bb = ByteBuffer.allocate(16); bb.putDouble(0, Math.random()); bb.putDouble(8, Math.random()); String input = Hex.encodeHexString(bb.array());

How to do same way in iOS (Swift or Objective-C) and What is the equivalent of ByteBuffer in iOS ?

Karthik Mandava
  • 507
  • 1
  • 14
  • 27

1 Answers1

2

I believe the object you are looking for is Data. It is an object that can represent any data and holds raw byte buffer.

For your specific case you need to convert array of double values to data which can be done like this:

let data: Data = doubleArray.withUnsafeBufferPointer { Data(buffer: $0) }

Now to get the hex string from Data I suggest you reference some other post.

Adding this answer code you should be able to construct your hex string by doing

let hexString = data.hexEncodedString()

So to put it ALL together you would do:

extension Data {
    struct HexEncodingOptions: OptionSet {
        let rawValue: Int
        static let upperCase = HexEncodingOptions(rawValue: 1 << 0)
    }

    func hexEncodedString(options: HexEncodingOptions = []) -> String {
        let format = options.contains(.upperCase) ? "%02hhX" : "%02hhx"
        return map { String(format: format, $0) }.joined()
    }
}

func generateRandomDoubleBufferHexString(count: Int, randomParameters: (min: Double, max: Double, percision: Int) = (0.0, 1.0, 100000)) -> String {

    func generateRandomDouble(min: Double = 0.0, max: Double = 1.0, percision: Int = 100000) -> Double {
        let scale: Double = Double(Int(arc4random())%percision)/Double(percision)
        return min + (max-min)*scale
    }

    var doubleArray: [Double] = [Double]() // Create empty array
    // Fill array with random values
    for _ in 0..<count {
        doubleArray.append(generateRandomDouble(min: randomParameters.min, max: randomParameters.max, percision: randomParameters.percision))
    }

    // Convert to data:
    let data: Data = doubleArray.withUnsafeBufferPointer { Data(buffer: $0) }

    // Convert to hex string
    return data.hexEncodedString()
}
Matic Oblak
  • 16,318
  • 3
  • 24
  • 43