Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

100 строки
2.9 KiB
C++

#include <iostream>
#include <cassert>
#include <cstdint>
using namespace std;
// Преобразование значения от 0 до 15 в шестнадцатеричную цифру
char nibble_to_hex(uint8_t i) {
assert(0x0 <= i && i <= 0xf);
const char digits[] = "0123456789abcdef";
return digits[i];
}
// Извлечение младшего nibble
uint8_t get_lower_nibble(uint8_t byte) {
return byte & 0x0f; // Младшие 4 бита
}
// Извлечение старшего nibble
uint8_t get_upper_nibble(uint8_t byte) {
return (byte >> 4) & 0x0f; // Старшие 4 бита
}
// Печать байта в шестнадцатеричном виде
void print_in_hex(uint8_t byte) {
cout << nibble_to_hex(get_upper_nibble(byte))
<< nibble_to_hex(get_lower_nibble(byte));
}
// Преобразование void* в uint8_t*
const uint8_t* as_bytes(const void* data) {
return reinterpret_cast<const uint8_t*>(data);
}
// Печать блока данных в шестнадцатеричном виде
void print_in_hex(const void* data, size_t size) {
const uint8_t* bytes = as_bytes(data);
for (size_t i = 0; i < size; i++) {
print_in_hex(bytes[i]);
// Для удобства чтения: пробелы между байтами, по 16 байт на строку.
if ((i + 1) % 16 == 0) {
cout << '\n';
} else {
cout << ' ';
}
}
cout << '\n'; // Завершение последней строки
}
// Печать байта в двоичном виде
char bit_digit(uint8_t byte, uint8_t bit) {
return (byte & (0x1 << bit)) ? '1' : '0';
}
void print_in_binary(uint8_t byte) {
for (uint8_t bit = 7; bit < 8; bit--) { // С 7 до 0
cout << bit_digit(byte, bit);
}
}
// Печать блока данных в двоичном виде
void print_in_binary(const void* data, size_t size) {
const uint8_t* bytes = as_bytes(data);
for (size_t i = 0; i < size; i++) {
print_in_binary(bytes[i]);
// Для удобства чтения: пробелы между байтами, по 4 байта на строку.
if ((i + 1) % 4 == 0) {
cout << '\n';
} else {
cout << ' ';
}
}
cout << '\n'; // Завершение последней строки
}
// Тестирование функции nibble_to_hex
void test_nibble_to_hex() {
for (uint8_t i = 0; i < 16; i++) {
assert(nibble_to_hex(i) == "0123456789abcdef"[i]);
}
}
int main() {
// Тестирование функций
test_nibble_to_hex();
uint8_t byte = 0xab;
cout << "Hex: ";
print_in_hex(byte);
cout << "Binary: ";
print_in_binary(byte);
uint32_t u32 = 0x42;
cout << "u32 bytes in hex: ";
print_in_hex(&u32, sizeof(u32));
cout << "u32 bytes in binary: ";
print_in_binary(&u32, sizeof(u32));
return 0;
}