zoukankan      html  css  js  c++  java
  • C语言学习(四)

    面试题中二进制转换问题,将一个二进制数,从某位开始进行,n位转换,程序如下所示:

     1 /************************************************************************/
     2 /* 功能:实现二进制数X的转化,p为转化位数,n为转化长度。例x=0b0001 0001,p=4,n=3转换后x=0b0110 0001
     3 /* 作者:ZL
     4 /* 日期:2018-04-08   14:38                                                                 
     5 /************************************************************************/
     6 
     7 #include <stdio.h>
     8 
     9 unsigned int convert(unsigned int x,int p,int n);
    10 void D_TO_B(unsigned int x);
    11 
    12 
    13 int main(void)
    14 {
    15     
    16    unsigned int x=17;
    17    unsigned int y;
    18 
    19    printf("转换前:");
    20    D_TO_B(x);
    21    printf("
    ");
    22 
    23    y=convert(x,4,3);
    24    printf("转换后:");
    25    D_TO_B(y);
    26    printf("
    ");
    27    
    28   
    29        
    30 }
    31 
    32 
    33 unsigned int convert(unsigned int x,int p,int n)
    34 {
    35     unsigned int Bit=0;
    36     unsigned int temp=1;
    37     int i=0;
    38 
    39     for (i=0;i<n;i++)
    40     {
    41         Bit |=temp;
    42         temp<<=1;
    43     }
    44 
    45     Bit=Bit<<p;
    46     x ^=Bit;
    47     return x;
    48 }
    49 
    50 void D_TO_B(unsigned int x)
    51 {
    52     int i=0,j=0;
    53     if (x==0)
    54     {
    55        return;
    56     }
    57     else
    58     {
    59       i=x%2;
    60       j=x/2;
    61       D_TO_B(j);
    62       printf("%d",i);
    63     }
    64 }

    程序在VC++6.0中运行结果如下图所示:

     

  • 相关阅读:
    微信H5跳转到小程序
    对比React的hooks与Vue的composition
    H5网页在ios,android,微信中打开手机中的地图导航
    MySQL学习笔记(一)
    Matlab学习笔记(五)
    Matlab学习笔记(四)
    Matlab学习笔记(三)
    Matlab学习笔记(二)
    Matlab学习笔记(一)
    Python学习笔记(四)
  • 原文地址:https://www.cnblogs.com/xuelanga000/p/8761395.html
Copyright © 2011-2022 走看看