Created
February 24, 2023 15:53
-
-
Save RodrigoDornelles/5968dbf7040d0b73def59417c1e1682a to your computer and use it in GitHub Desktop.
bidirectional converter between gray and binary
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @file graybin.c | |
* @author Rodrigo Dornelles | |
* @link https://en.wikipedia.org/wiki/Gray_code | |
*/ | |
#include <stdio.h> | |
#include <stdint.h> | |
/** | |
* @brief bidirectional converter between gray and binary | |
* | |
* @param in | |
* @return uint32_t | |
*/ | |
uint32_t graybin(uint32_t in) | |
{ | |
uint32_t out = in >> 1; | |
out ^= in; | |
return out; | |
} | |
/** | |
* @brief print boolean format | |
* | |
* @param in | |
*/ | |
void printb(uint32_t in) | |
{ | |
uint8_t i = 31; | |
do { | |
putc('0' + ((in >> i) & 1), stdout); | |
} | |
while(i--); | |
putc('\n', stdout); | |
} | |
int main() | |
{ | |
printb(graybin(0b11)); ///< [2] gray -> bin | |
printb(graybin(0b10)); ///< [2] bin -> gray | |
printb(graybin(graybin(0b11))); ///< [2] gray -> bin -> gray | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment