Created
March 24, 2024 22:37
-
-
Save haseeb-heaven/d5f55f6c63f73a083f706d6236677b90 to your computer and use it in GitHub Desktop.
Welcome to Heaven's Endianness Number Analyzer!
This file contains hidden or 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
#include <iostream> | |
#include <bitset> | |
#include <stdexcept> | |
#include <iomanip> | |
// Function to check if the system is little endian | |
bool isSystemLittleEndian() { | |
int testNumber = 1; | |
return *(char*)&testNumber == 1; | |
} | |
// Function to print the byte at a specific index of a number in both decimal, binary and hexadecimal | |
void printByteAtIndex(int index, std::uint64_t number) { | |
if (index < 0 || index >= sizeof(std::uint64_t)) { | |
throw std::out_of_range("Index out of range"); | |
} | |
// Get the byte at the specified index | |
unsigned char byte = reinterpret_cast<unsigned char*>(&number)[index]; | |
// Convert the byte to a bitset to get its binary representation | |
std::bitset<8> binaryRepresentation(byte); | |
// Print the byte in decimal, binary and hexadecimal in a tabular format | |
std::cout << std::setw(5) << index+1 | |
<< std::setw(10) << static_cast<unsigned>(byte) | |
<< std::setw(15) << binaryRepresentation | |
<< std::setw(15) << std::hex << std::uppercase << static_cast<unsigned>(byte) << std::dec | |
<< std::endl; | |
} | |
int main() { | |
try { | |
std::uint64_t numberToAnalyze; | |
std::cout << "Welcome to Heaven's Endianness Number Analyzer!" << std::endl; | |
std::cout << "Number to analyze: "; | |
std::cin >> numberToAnalyze; | |
// Print the header of the table | |
std::cout << std::setw(5) << "Byte" | |
<< std::setw(10) << "Decimal" | |
<< std::setw(15) << "Binary" | |
<< std::setw(15) << "Hexa" | |
<< std::endl; | |
// Print the bytes of the number in the order determined by the system's endianness | |
if (isSystemLittleEndian()) { | |
for(int index = 0; index < sizeof(std::uint64_t); index++) { | |
printByteAtIndex(index, numberToAnalyze); | |
} | |
} else { | |
for(int index = sizeof(std::uint64_t) - 1; index >= 0; index--) { | |
printByteAtIndex(index, numberToAnalyze); | |
} | |
} | |
return EXIT_SUCCESS; | |
} catch (const std::exception& exception) { | |
std::cerr << "Error: " << exception.what() << std::endl; | |
return EXIT_FAILURE; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Welcome to Heaven's Endianness Number Analyzer!
Number to analyze: 655455