/*
* This request is similar reverse bit in another request
* -> check reverse_bit_tg. However that coding is for 2 cases:
* - Reverse FULL 32 bits
* - Reverse exact the number counted from first bit 1 to end (ex: 0x3A --> b'11 1010)
*
* In this request will reverse exactly input from user as 0x3A
*/
/* Include lib */
#include <stdio.h>
#include <assert.h>
#include <string.h>
/* Define */
/* API display with bit presentation */
void bit_display_from_input(int hex_num, int bit_cnt)
{
int i;
for (i = (bit_cnt - 1); i >= 0 ; i--) {
printf("%d", (hex_num >> i) & 0x1);
}
}
/* API reverse bit from USER input */
int reverse_hex_input(int hex_num, int bit_cnt)
{
int i, tmp, ret = 0;
for (i = 0; i < bit_cnt; i++) {
tmp = (hex_num >> i) & 0x1;
ret = (ret << 1) | tmp;
}
return ret;
}
/* Main func interract with user */
int main(void)
{
int sel, hex_num, bit_cnt, ret;
char str[32] = { 0 };
while (1) {
printf("\n\nSelection: \n");
printf("0 : input hex number to reverse\n");
printf("1 : Exit\n");
printf("Select: ");
scanf("%d", &sel);
if (sel == 0) {
printf("Input hex (without '0x'): ");
scanf("%x", &hex_num);
/* TODO: Write func or get lib to convert string to number */
#if 0
printf("Input bit cnt: ");
scanf("%d", &bit_cnt);
#else
sprintf(str, "%x", hex_num);
bit_cnt = strlen(str) * 4;
#endif
/* Reverse */
ret = reverse_hex_input(hex_num, bit_cnt);
/* Print hex */
printf("0x%x => 0x%x \n", hex_num, ret);
/* Print bin */
bit_display_from_input(hex_num, bit_cnt);
printf(" => ");
bit_display_from_input(ret, bit_cnt);
} else {
return 0;
}
}
return -1;
}
To embed this project on your website, copy the following code and paste it into your website's HTML: