本文共 1071 字,大约阅读时间需要 3 分钟。
C/C++ code#include
#include
#include
typedef struct
{
unsigned char bit_1 : 1;
unsigned char bit_2 : 1;
unsigned char bit_3 : 1;
unsigned char bit_4 : 1;
unsigned char bit_5 : 1;
unsigned char bit_6 : 1;
unsigned char bit_7 : 1;
unsigned char bit_8 : 1;
}bit;
void Dec2Bin(int *a,char *b,int n=1) //将数据转换为N个字节,默认为1个字节
{
bit *p_bit;
int j;
p_bit=(bit *)a;
for(j=n-1;j>=0;j--)
{
*b++=(p_bit+j)->bit_8;
*b++=(p_bit+j)->bit_7;
*b++=(p_bit+j)->bit_6;
*b++=(p_bit+j)->bit_5;
*b++=(p_bit+j)->bit_4;
*b++=(p_bit+j)->bit_3;
*b++=(p_bit+j)->bit_2;
*b++=(p_bit+j)->bit_1;
}
}
void StrTurn(char *str,int n=1) //将N个字节倒序排列,默认为1个字节
{
char *p,*q;
char temp;
p=str;
q=str+n*8-1;
while(p
{
temp=*p;
*p=*q;
*q=temp;
p++;
q--;
}
}
int main()
{
int a,i,n;
char *b;
while(printf("请输入要转换的数据和字节数:\n"),scanf("%d%d",&a,&n)!=0)
{
b=(char *)malloc(n*8+1);
memset(b,2,n*8+1);
Dec2Bin(&a,b,n);
printf("%d的二进制形式为:\n",a);
for(i=0;b[i]!=2;i++)
printf("%d ",b[i]);
printf("\n\n");
StrTurn(b,n);
printf("翻转后%d的二进制形式为:\n",a);
for(i=0;b[i]!=2;i++)
printf("%d ",b[i]);
printf("\n\n\n");
free(b);
}
return 0;
}
转载地址:https://blog.csdn.net/weixin_31881743/article/details/117013446 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!