Question

I want to transmit data in bytes and at receiver side want to generate the same NSData object back. My data size can keep on changing. I am able to define the correct length to be used on receiver side to generate the same object back.

NSDictionary *aWritableFields = @{@"Data1": @"1", @"Data2": @"2", @"Data3": @"3", @"Data4" : @"4"};
NSData *aData = [NSJSONSerialization dataWithJSONObject:aWritableFields options:0 error:nil];
uint32_t *bytes = (uint32_t *)aData.bytes;

On the receiver end, I want to construct the same NSData object back. For this I am using following method but this is giving me extra information. How should I define the length so that it gives me just the right NSData object.

[NSData dataWithBytes:iBytes length:sizeof(uint32_t)*24];

The data object I sent was:

<7b225555 4944223a 2231222c 224d696e 6f72223a 2231222c 22506f77 6572223a 2233222c 224d616a 6f72223a 2232227d>

But on receiver end I get because of excessive length:

<7b225555 4944223a 2231222c 224d696e 6f72223a 2231222c 22506f77 6572223a 2233222c 224d616a 6f72223a 2232227d a3a3a3a3 a3a3a3a3 a3a3a3a3 a3a3a3a3 a3a3a3a3 a3a3a3a3 a3a3a3a3 a3a3a3a3 a3a3a3a3 a3a3a3a3 a3a3a3a3 a3a3a3a3>

Was it helpful?

Solution

The receiver has to know the exact number of bytes. How that is achieved depends on which protocol is used to transmit the data from the sender to the receiver. In the case of HTTP, it could be deduced from the Content-Length: header. If you send only one message from sender to receiver, the receiver could count the number of bytes until EOF. Or you transmit the number of bytes together with the actual data.

But the receiver can not determine the correct length from the pure bytes alone.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top