From 770a4d553b638e2d1948e8b4a9e4d412c46ae377 Mon Sep 17 00:00:00 2001 From: PvlukhinaYA Date: Wed, 25 Dec 2024 23:02:37 +0300 Subject: [PATCH] =?UTF-8?q?=D0=97=D0=B0=D0=B4=D0=B0=D0=BD=D0=B8=D0=B5=5F1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- lab04_1.cpp | 119 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 119 insertions(+) create mode 100644 lab04_1.cpp diff --git a/lab04_1.cpp b/lab04_1.cpp new file mode 100644 index 0000000..e1e7cb9 --- /dev/null +++ b/lab04_1.cpp @@ -0,0 +1,119 @@ +#include +#include +#include + +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; +} + +// Извлечение старшего nibble +uint8_t get_upper_nibble(uint8_t byte) +{ + return byte >> 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(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]); + if ((i + 1) % 16 == 0) + { + cout << '\n'; + } + else + { + cout << ' '; + } + } +} + +// Печать байта в двоичном виде +void print_in_binary(uint8_t byte) +{ + for (int bit = 7; bit >= 0; --bit) + { + cout << ((byte & (1 << bit)) ? '1' : '0'); + } +} + +// Печать блока данных в двоичном виде +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]); + if ((i + 1) % 4 == 0) + { + cout << '\n'; + } + else + { + cout << ' '; + } + } +} + +int main() +{ + // Самопроверка nibble_to_hex() + for (uint8_t i = 0; i < 16; i++) + { + assert(nibble_to_hex(i) == (i < 10 ? '0' + i : 'a' + (i - 10))); + } + + // Примерные данные для тестирования + uint8_t byte = 0xab; + + // Печать в шестнадцатеричном виде + cout << "Hex: "; + print_in_hex(byte); + cout << '\n'; + + // Печать в двоичном виде + cout << "Binary: "; + print_in_binary(byte); + cout << '\n'; + + // Примеры печати структур разных типов + uint32_t u32 = 0x42; + cout << "u32 bytes in hex: "; + print_in_hex(&u32, sizeof(u32)); + cout << '\n'; + + cout << "u32 bytes in binary: "; + print_in_binary(&u32, sizeof(u32)); + cout << '\n'; + + return 0; +} \ No newline at end of file