C language learning: conversion of binary code and gray code

Gray code is also called circular binary code or reflected binary code. Gray code is a coding method we often encounter in engineering. Its basic characteristic is that any two adjacent codes only differ by one binary number.

The basic feature of Gray code is that any two adjacent codes only differ by one binary number, which is very important. The conversion relationship between commonly used binary numbers and Gray codes is as follows:

Binary code conversion to binary Gray code

Binary code is converted into binary Gray code. The rule is to reserve the highest bit of the binary code as the highest bit of the Gray code, while the second highest bit of the Gray code is the XOR of the high bit and the next highest bit of the binary code, and the remaining bits of the Gray code are the same as the next highest bit. The method is similar.

Code:

#include<iostream>

#include <bitset>

using namespace std;



int D2G(int x)

{

    return x^(x>>1);

}



int main()

{

    int x;

    cin>>x;

    cout<<D2G(x);

    //注意输入与输出均为十进制

}

Gray code converted to binary code

Binary Gray code is converted into binary code. The rule is to retain the highest bit of Gray code as the highest bit of natural binary code, and the second-highest natural binary code is the XOR of the high-order natural binary code and the second-highest Gray code, and the natural binary code’s The rest of the bits are similar to the second-highest natural binary code.

 


In addition, if you want to better improve your programming ability, learn C language and C++ programming! Overtaking in a curve, one step faster! I may be able to help you here~

UP has uploaded some video tutorials on learning C/C++ programming on the homepage. Those who are interested or are learning must go and take a look! It will be helpful to you~

Sharing (source code, actual project video, project notes, basic introductory tutorial)

Welcome partners who change careers and learn programming, use more information to learn and grow faster than thinking about it yourself!

Programming learning:

Programming learning:

Guess you like

Origin blog.csdn.net/weixin_45713725/article/details/114696786