gpt4 book ai didi

android - ios低级序列化

转载 作者:行者123 更新时间:2023-11-29 13:05:53 27 4
gpt4 key购买 nike

这是一个 Java/Android 函数:

public static byte[] serialize(MyClass myObject) {

int byteArraySizeNeeded = getByteArraySizeNeededForSerialize(myObject);

byte[] result = new byte[byteArraySizeNeeded];
ByteBuffer bb = ByteBuffer.wrap(result);
bb.putShort((short) (byteArraySizeNeeded-2));// 2 - not need to read at deserialisation!

bb.putLong(myObject.getProperty1ValueWhichIsALong());// 8
bb.putDouble(myObject.getProperty2ValueWhichIsADouble());// 8
bb.putFloat(myObject.getProperty3ValueWhichIsAFloat);//4
bb.put(CODE_MYCODE1); // code
bb.putFloat(myObject.getProperty4ValueWhichIsAFloat);

// there are a lot of properties and the list is dynamic: some need to be saved some not: eg if property 10 exists than not needed to save property 11 and property 25 is saved only if not null and so on.

int curPosition = bb.position();
int offset = 2; // skip the first 2 bytes representing the size of byte buffer needed to allocate.
int byteCount = curPosition - offset;

myObject.crc.update(result, offset, byteCount);
long crcValue = myObject.crc.getValue();

bb.put(CODE_CRC); // code
bb.putLong(crcValue);// only distinct data values

return result;
}

我也想在 iOS 上做。或者我想念或找不到要使用的低级数据结构/类。

NSDataNSMutableData声称是一个包装字节数组的对象,但它们有用的功能只是dataContentsOfFilewriteToFile .

NSArchiver就像一个 ObjectOutputStream。

Archives and Serializations Programming Guide找不到任何不需要像 encodeBytes:length:forKey:

这样的 key 的方法

我不想重新发明轮子,也不想在保存时使用大量不必要的数据。

是否有任何具有 putLong() putFloat() putInt() 并正确生成字符或字节数组的实用程序类?

最佳答案

我找到了 the same question这个答案是基于它的。您可以使用 NSOutputStream 轻松创建一个实现与 ByteBuffer 相同接口(interface)的类。 .像这样:

- (NSOutputStream*)outputStream {
if (_outputStream == nil) {
_outputStream = [[NSOutputStream alloc] initToMemory];
[_outputStream open];
}
return _outputStream;
}

- (void)putInt:(NSInteger)value {
[self.outputStream write:(uint8_t*)&value maxLength:sizeof(NSInteger)];
}

- (NSData*)data {
return [self.outputStream propertyForKey:NSStreamDataWrittenToMemoryStreamKey];
}

关于android - ios低级序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18656416/

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