[英]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我使用GCDAsyncSocket实现iOS中的socket,我收到package头首先使用
socket.readData(toLength: 5, withTimeout: -1, tag: 0)
然后我将在didRead
委托中计算主体长度并使用socket.readData(toLength: bodySize, withTimeout: -1, tag: 0)
继续接收正文 package
The head of socket package have 5 bytes bytes[0] is type,and other four bytes is the size of body socket package 的头部有 5 个字节 bytes[0] 是类型,其他四个字节是 body 的大小
Size is convert from Int to bytes in java大小从 Int 转换为 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 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 )所以我想知道如何将大小字节转换为 Int
When you have 5 bytes in a Data
, you have no need to convert it to an Array
.如果
Data
中有 5 个字节,则无需将其转换为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.还有其他一些方法,但此代码适合您的 Java 代码的逆运算。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.