Join our subscribers list to get the latest news, updates and special offers directly in your inbox
Overview
Statement
Reverse a hexadecimal number like 0x12345678 into 0x78563412 by reversing its bytes (not just the bits or nibbles)
#include "stdint.h" #include "stdio.h" uint8_t Find_Number_Of_Bytes_Non_Zero(uint32_t hex) { uint8_t countBytes = 0; while(hex != 0) { hex = hex >> 8; countBytes++; } return countBytes; } uint32_t Reverse_Hex_Bytes(uint32_t hex, size_t numBytes) { uint32_t reversed = 0; for (size_t i = 0; i < numBytes; i++) { unsigned int byte = (hex >> (i * 8)) & 0xFF; reversed |= byte << ((numBytes - 1 - i) * 8); } return reversed; } int main() { uint32_t hex1 = 0x123456; uint32_t hex2 = 0x12345678; size_t numBytes1 = Find_Number_Of_Bytes_Non_Zero(hex1); size_t numBytes2 = Find_Number_Of_Bytes_Non_Zero(hex2); uint32_t reverse1 = Reverse_Hex_Bytes(hex1, numBytes1); uint32_t reverse2 = Reverse_Hex_Bytes(hex2, numBytes2); printf("Original 16-bit: 0x%X, Reversed 16-bit: 0x%X\n", hex1, reverse1); printf("Original 32-bit: 0x%X, Reversed 32-bit: 0x%X\n", hex2, reverse2); return 0; }
#include : Includes the standard input/output library for functions like printf.#include : Includes the standard integer types library for defining fixed-width integer types like uint8_t and uint32_t.
1. Find_Number_Of_Bytes_Non_Zero(uint32_t hex):
2. Reverse_Hex_Bytes(uint32_t hex, size_t numBytes):
The code effectively performs the following tasks:
EmbeddedWala
EmbeddedWala Apr 27, 2023 0 17.1K
EmbeddedWala Jun 14, 2023 0 16.2K
EmbeddedWala Apr 26, 2023 0 15.3K
EmbeddedWala Aug 30, 2022 0 13.9K
EmbeddedWala Apr 27, 2023 0 13.7K
EmbeddedWala Jun 19, 2022 0 4.2K
This site uses cookies. By continuing to browse the site you are agreeing to our use of cookies Find out more here