牛骨文教育服务平台(让学习变的简单)
博文笔记

byte字节转换成int类型

创建时间:2015-11-04 投稿人: 浏览次数:5471

将高位字节转换为int

-(int )heightBytesToInt:(Byte[]) byte
{
    int height = 0;
    for (int i = 0; i < [testData length]; i++)
    {
        if (byte[i] >= 0)
        {
            height = height + byte[i];
        } else
        {
            height = height +256 + byte[i];
        }
        height = height * 256;
        if (byte[3] >= 0)
        {
            height = height + byte[3];
        } else
        {
            height = height + 256 + byte[3];
        }

    }
    return height;
}

将低位字节转换为int
在网络上传输的是以低位字节进行的; htonl,将int转换为网络字节序的int,ntohl,将网络字节序的int转换回来,-(int) lBytesToInt:(Byte[]) b,将以低位传输的网络字节序bytes数组转换为htonl之后对应的值

-(int) lBytesToInt:(Byte[]) byte
{
    int height = 0;
    for (int i = 0; i < [testData length]; i++)
    {
        if (byte[[testData length]-i] >= 0)
        {
            height = height + byte[[testData length]-i];
            NSLog(@"%d",height);
        } else
        {
            height = height + 256 + byte[[testData length]-i];
        }
        height = height * 256;
    }
    if (byte[0] >= 0)
    {
        height = height + byte[0];
    } else {
        height = height + 256 + byte[0];
    }
    return height;
}
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。