swiftgcdasyncsocket

How to convert the java bytes to swift int


I use GCDAsyncSocket to achieve the socket in iOS , I receive the package head first use socket.readData(toLength: 5, withTimeout: -1, tag: 0) then I will calculate the body length in didRead delegate and use socket.readData(toLength: bodySize, withTimeout: -1, tag: 0) to continued receive body package

The head of socket package have 5 bytes bytes[0] is type ,and other four bytes is the size of body

Size is convert from Int to bytes in java

 byte[] header = new byte[5];
 header[0] = type; //package type 
 header[1]=(byte) ((length>>24)&0xff);  //package size 
 header[2]=(byte) ((length>>16)&0xff);  //package size
 header[3]=(byte) ((length>>8)&0xff);  //package size
 header[4]=(byte) (length&0xff);       //package size
 return header;

In swift I use let bytes = [UInt8](data) to convert the data to bytes in socket(_ sock: GCDAsyncSocket, didRead data: Data, withTag tag: Int) Because the bytes array in swift is UInt8 and different with java bytes( -127 ~ 127 ) So I want to know How to convert the size bytes to Int


Solution

  • When you have 5 bytes in a Data, you have no need to convert it to an Array.

    You can write something like this:

    let length = UInt32(data[1]) << 24 | UInt32(data[2]) << 16 | UInt32(data[3]) << 8 | UInt32(data[4])
    

    There are some other ways, but this code would fit for the inverse operation of your Java code.