As part of my projects, I have a binary data file consisting of a large series of 32-bit integers that one of my classes reads during initialization. In my C ++ library, I read it with the following initializer:
Evaluator::Evaluator() { m_HandNumbers.resize(32487834); ifstream inputReader; inputReader.open("/path/to/file/7CHands.dat", ios::binary); int inputValue; for (int x = 0; x < 32487834; ++x) { inputReader.read((char *) &inputValue, sizeof (inputValue)); m_HandNumbers[x] = inputValue; } inputReader.close(); };
and when transferring to Swift, I decided to read the entire file into one buffer (this is only about 130 MB), and then copied the bytes from the buffer.
So, I did the following:
public init() { var inputStream = NSInputStream(fileAtPath: "/path/to/file/7CHands.dat")! var inputBuffer = [UInt8](count: 32478734 * 4, repeatedValue: 0) inputStream.open() inputStream.read(&inputBuffer, maxLength: inputBuffer.count) inputStream.close() }
and it works fine when I debug it, I see that inputBuffer contains the same byte array as my hex editor. Now I would like this data to be effective. I know that it is stored in any format that you call it, where the least significant bytes are first (that is, the Number 0x00011D4A is represented as "4A1D 0100" in the file). I am tempted to simply iterate over it manually and calculate the byte values ββmanually, but I wonder if it is possible to quickly transfer an array from [Int32] and read these bytes. I tried using NSData, for example:
let data = NSData(bytes: handNumbers, length: handNumbers.count * sizeof(Int32)) data.getBytes(&inputBuffer, length: inputBuffer.count)
but this did not seem to load the values ββ(all values ββwere still null). Can someone help me convert this byte array to some Int32 values? It would be best to convert them to Int (i.e. a 64-bit integer) in order to maintain the same variable sizes in the project.
source share