zoukankan      html  css  js  c++  java
  • c语言中unsigned类型和普通类型间的转换

      最近在做一个项目的过程中,遇到了协议的加密解密和封装,其中经常遇到unsigned类型的数据和普通数据类型间转来转去,所以经过研究,简单封装了几个函数,在这里分享给大家,有不足之处还望大家给予指正。

    unsigned short unCharToUnShort(unsigned char* pBuf)
    {
     unsigned short result = 0;
     result = (short)pBuf[0]*256;
     result += (short)pBuf[1];
     return result;
    }

    unsigned int unCharToUnInt(unsigned char* pBuf)
    {
     unsigned int result = 0;
     result = (short)pBuf[0]*256*256*256;
     result += (short)pBuf[1]*256*256;
     result += (short)pBuf[2]*256;
     result += (short)pBuf[3];
     return result;
    }

      以上两个函数是把unsigned char*转换为unsigned short或unsigned int,数据的存放方式为高字节在前,低字节在后,比如无符号短整型256是0x01 0x00。我们通过依次获取低位的数据然后乘以0xFF,来获取低位所代表的整数值,然后再把各个位的值相加,得出最终需要的无符号整形值。其中把一个字节强转为short型,就是为了获取该字节的无符号整型值,因为一个short值占两个字符,我们这样强转,其实只用了short高位的那一个字节。

    void unShortToUnChar(unsigned char* pBuf,unsigned short iValue)
    {
     pBuf[0] = (unsigned char)(iValue>>8);
     pBuf[1] = (unsigned char)(iValue);
    }

    void unIntToUnChar(unsigned char* pBuf,unsigned int iValue)
    {
     pBuf[0] = (unsigned char)(iValue>>24);
     pBuf[1] = (unsigned char)(iValue>>16);
     pBuf[2] = (unsigned char)(iValue>>8);
     pBuf[3] = (unsigned char)(iValue);
    }

      以上两个函数作用是把无符号整形转换为unsigned char型。所使用的方式是把整型值右移8的倍数,然后取高位强转为unsigned char后赋值给我们的unsigned char数组中的各个字节。

      在做无符号数据类型和有符号数据类型转换的时候方式有很多,此处介绍的是我觉得比较简单且易懂的,代码已在VS和linux下测试通过。大家如果有更好的方式,欢迎跟帖交流,我好对本文章进行更新,方便其它同仁学习。

  • 相关阅读:
    poj1330 Nearest Common Ancestors
    poj3237 Tree
    spoj2798 QTREE3 Query on a tree again!
    spoj913 QTREE2 Query on a treeⅡ
    自动类型转换
    js "+"连接符号
    js parseFloat
    js字符串与数字的运算
    js prompt
    js数组排序
  • 原文地址:https://www.cnblogs.com/osyun/p/2097199.html
Copyright © 2011-2022 走看看