Skip to content

Instantly share code, notes, and snippets.

@haseeb-heaven
Created March 24, 2024 22:37
Show Gist options
  • Save haseeb-heaven/d5f55f6c63f73a083f706d6236677b90 to your computer and use it in GitHub Desktop.
Save haseeb-heaven/d5f55f6c63f73a083f706d6236677b90 to your computer and use it in GitHub Desktop.
Welcome to Heaven's Endianness Number Analyzer!
#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;
}
}
@haseeb-heaven
Copy link
Author

Welcome to Heaven's Endianness Number Analyzer!
Number to analyze: 655455

 Byte   Decimal         Binary           Hexa
    1        95       01011111             5F
    2         0       00000000              0
    3        10       00001010              A
    4         0       00000000              0
    5         0       00000000              0
    6         0       00000000              0
    7         0       00000000              0
    8         0       00000000              0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment