Родитель
e959051d3f
Сommit
8f476f0fe7
@ -1,68 +0,0 @@
|
||||
#include <iostream>
|
||||
#include <cassert>
|
||||
#include <cstdint>
|
||||
using namespace std;
|
||||
|
||||
// Преобразует число от 0 до 15 в символ шестнадцатеричной системы
|
||||
char to_hex_digit(uint8_t value) {
|
||||
assert(value < 16);
|
||||
const char hex_chars[] = "0123456789abcdef";
|
||||
return hex_chars[value];
|
||||
}
|
||||
|
||||
// Возвращает символ, представляющий бит ('0' или '1')
|
||||
char get_bit_char(uint8_t byte, uint8_t pos) {
|
||||
return (byte & (1 << pos)) ? '1' : '0';
|
||||
}
|
||||
|
||||
// Преобразует указатель на void в указатель на uint8_t
|
||||
const uint8_t* to_byte_array(const void* ptr) {
|
||||
return static_cast<const uint8_t*>(ptr);
|
||||
}
|
||||
|
||||
// Выводит байт в шестнадцатеричном формате
|
||||
void display_hex_byte(uint8_t byte) {
|
||||
cout << to_hex_digit(byte >> 4) << to_hex_digit(byte & 0x0F);
|
||||
}
|
||||
|
||||
// Выводит данные в шестнадцатеричном формате
|
||||
void display_hex_data(const void* data, size_t length) {
|
||||
const uint8_t* bytes = to_byte_array(data);
|
||||
for (size_t idx = 0; idx < length; ++idx) {
|
||||
display_hex_byte(bytes[idx]);
|
||||
cout << ((idx + 1) % 16 == 0 ? '\n' : ' ');
|
||||
}
|
||||
}
|
||||
|
||||
// Выводит байт в двоичном формате
|
||||
void display_binary_byte(uint8_t byte) {
|
||||
for (int pos = 7; pos >= 0; --pos) {
|
||||
cout << get_bit_char(byte, pos);
|
||||
}
|
||||
}
|
||||
|
||||
// Выводит данные в двоичном формате
|
||||
void display_binary_data(const void* data, size_t length) {
|
||||
const uint8_t* bytes = to_byte_array(data);
|
||||
for (size_t idx = 0; idx < length; ++idx) {
|
||||
display_binary_byte(bytes[idx]);
|
||||
cout << ((idx + 1) % 4 == 0 ? '\n' : ' ');
|
||||
}
|
||||
}
|
||||
|
||||
// Пример использования функций
|
||||
int main() {
|
||||
assert(to_hex_digit(0x0) == '0');
|
||||
assert(to_hex_digit(0xA) == 'a');
|
||||
assert(to_hex_digit(0xF) == 'f');
|
||||
|
||||
uint32_t sample = 0x42;
|
||||
cout << "Hexadecimal representation:\n";
|
||||
display_hex_data(&sample, sizeof(sample));
|
||||
|
||||
cout << "\n\nBinary representation:\n";
|
||||
display_binary_data(&sample, sizeof(sample));
|
||||
cout << '\n';
|
||||
|
||||
return 0;
|
||||
}
|
Загрузка…
Ссылка в новой задаче