添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

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 ?

@KarthikMandava: If your actual problem is to create a random array of bytes then please update the question (and title) accordingly. That can be done in Swift. Martin R Sep 11, 2018 at 11:18

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()
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.