移位操作及其在数据类型转换中的作用

一.对移位操作的基本概述:

1、什么样的数据类型可以直接移位

char、short、int、long、unsigned char、unsigned short、unsigned int、unsigned long都可以进行移位操作,而double、float、bool、long double则不可以进行移位操作。

 

2、有符号数据类型的移位操作

对于char、short、int、long这些有符号的数据类型:

对负数进行左移:符号位始终为1,其他位左移

对正数进行左移:所有位左移,即 <<,可能会变成负数

对负数进行右移:取绝对值,然后右移,再取相反数

对正数进行右移:所有位右移,即 >>

 

3、无符号数据类型的移位操作

对于unsigned char、unsigned short、unsigned int、unsigned long这些无符号数据类型:

没有特殊要说明的,使用<< 和 >> 操作符就OK了

结束语

8086 中存在逻辑移位、算术移位,而C\C++中的移位似乎既不是逻辑移位,也不是算术移位。

比如-1,我们若对它右移1位,C的结果仍旧是-1,事实上无论右移多少位始终是-1,逻辑移位得到的结果(8位表示)应该是-128,所以这点要注意。

二.利用移位操作实现不同数据类型的转换:

注:左移一位相当于*2,右移一位相当于除以2;

下面是实现long int 到unsigned char,及unsigned char 到short int转换的实例,在dev C++下面,已运行通过,请参考:

#include <stdio.h>

#include <malloc.h>

/*************************************************************************

NAME

   uint32Touint8

DESCRIPTION

    Unpack auint32 into an array of 4 uint8s

*************************************************************************/

void uint32Touint8(unsigned char *dest, unsigned longint src)

{

    *dest++ =src >> 24;

    *dest++ =(src >> 16) & 0xFF;

    *dest++ =(src >> 8) & 0xFF;

    *dest = src& 0xFF;

}

 

/*************************************************************************

NAME

   uint8Touint16

DESCRIPTION

    Pack anarray of 2n uint8s into an array of n uint16s

**************************************************************************/

void uint8Touint16(unsigned short int *dest, unsignedchar *src, unsigned short int n)

{

    while (n--)

    {

        *dest =*src++ << 8;

        *dest++|= *src++;

    }

}

int main()

{

    unsignedchar *dest1 = (unsigned char*)malloc(1);

    unsignedlong int src1 = 0x12345678;

    unsignedchar *src2 = (unsigned char*)malloc(2);

    unsignedshort int *dest2 = (unsigned short int *)malloc(1) ;

    *src2 =0x12;

    *(src2+1) =0x34;

   uint32Touint8(dest1,src1);

   uint8Touint16(dest2,src2,1);

    if(dest1 !=NULL)

    {

    for(int i=0;i<4; i++)

   printf("dest[%x] = 0x%x\n",i,dest1[i]);

   }/*dest[0]=0x12,dest[1]=0x34,dest[2]=0x56,dest[3]=0x78*/

    if(dest2 !=NULL)

    {

   printf("dest2 = 0x%x\n",*dest2++);

   }/*dest2=0x1234*/

    getchar();

    return 0;

    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值