Question

I'm developing an app which pass bytes through the network, the server declares its bytes order is Big-Endian. In my app, I wrap my data with a header which takes 2 bytes, I assign the byte as following :

int length = [self.dataLengthHeader length];
if (length <= 255) {
    high = 0;
    low = length;
}else if (length == 256)
{
    high = 1;
    low = 0;
}else {
    high = length/256;
    low = length%256;
}
Byte byte[] = {high, low};
NSLog(@"%hhu  %hhu", high, low);
NSMutableData *dataToSend = [NSMutableData dataWithBytes:byte length:2];

For examplethe first byte is 00, the second is 05

The first byte is 00(8 bits), the second is 05(8 bits)

Where another app receives the header, it parse the header which takes 2 bytes into two int(two NSInteger would be better) to get the information of the real message.

NSData *twoBytes = [NSData dataWithBytes:payloadptr length:2];

NSData *low = [twoBytes subdataWithRange:NSMakeRange(1, 1)];
int lowP;
[low getBytes:&lowP length:sizeof(lowP)];

NSData *high = [twoBytes subdataWithRange:NSMakeRange(0, 1)];
int highP;
[high getBytes:&highP length:sizeof(highP)];

Memory shortcut:the first byte

the second byte

When I log out the bytes, it turns out to be something like this:highP = 70074112 lowP = 365573 I can never get the correct result, anybody could help me?

Any help would be appreciated!

Was it helpful?

Solution

Read about serialization.

You could make yourself using e.g. htonl(3), or endian(3).

You could use XDR with RPCGEN, or ASN.1.

You could use libs11n (in C++). You could also consider protocol buffers, etc...

Unless you have a lot of data, or bandwidth, you may consider using textual serialization formats like JSON (there are somehow flexible, easier to debug, etc...) or binary counterparts like BSON. Notice that sending data on a network is much slower than your CPU, so the overhead of textual serialization is generally lost in the noise (even if you compress it).

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