Вы не можете выбрать более 25 тем
Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
92 строки
1.8 KiB
C++
92 строки
1.8 KiB
C++
#include <iostream>
|
|
#include <assert.h>
|
|
using namespace std;
|
|
|
|
char nibble_to_hex(uint8_t i)
|
|
{
|
|
char digits[] = "0123456789abcdef";
|
|
assert(0x0 <= i && i <= 0xf);
|
|
return digits[i];
|
|
}
|
|
|
|
void print_in_hex(uint8_t byte) {
|
|
cout << nibble_to_hex(byte >> 4)
|
|
<< nibble_to_hex(byte & 0xf);
|
|
}
|
|
|
|
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]);
|
|
|
|
if ((i + 1) % 16 == 0) {
|
|
cout << '\n';
|
|
}
|
|
else {
|
|
cout << ' ';
|
|
}
|
|
}
|
|
}
|
|
|
|
char bit_digit(uint8_t byte, uint8_t bit) {
|
|
if (byte & (0x1 << bit)) {
|
|
return '1';
|
|
}
|
|
return '0';
|
|
}
|
|
|
|
void print_in_binary(uint8_t byte) {
|
|
for (int bit = 7; bit >= 0; bit--) {
|
|
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]);
|
|
|
|
if ((i + 1) % 4 == 0) {
|
|
cout << '\n';
|
|
}
|
|
else {
|
|
cout << ' ';
|
|
}
|
|
}
|
|
}
|
|
|
|
int main()
|
|
{
|
|
|
|
assert(nibble_to_hex(0x0) == '0');
|
|
assert(nibble_to_hex(0x1) == '1');
|
|
assert(nibble_to_hex(0x1) == '2');
|
|
assert(nibble_to_hex(0x1) == '3');
|
|
assert(nibble_to_hex(0x1) == '4');
|
|
assert(nibble_to_hex(0x1) == '5');
|
|
assert(nibble_to_hex(0x1) == '6');
|
|
assert(nibble_to_hex(0x1) == '7');
|
|
assert(nibble_to_hex(0x1) == '8');
|
|
assert(nibble_to_hex(0x1) == '9');
|
|
assert(nibble_to_hex(0x1) == 'a');
|
|
assert(nibble_to_hex(0x1) == 'b');
|
|
assert(nibble_to_hex(0x1) == 'c');
|
|
assert(nibble_to_hex(0x1) == 'd');
|
|
assert(nibble_to_hex(0x1) == 'e');
|
|
assert(nibble_to_hex(0xf) == 'f');
|
|
uint32_t u32 = 0x42;
|
|
cout << "u32 bytes: ";
|
|
print_in_hex(&u32, sizeof(u32));
|
|
cout << '\n';
|
|
print_in_binary(&u32, sizeof(u32));
|
|
cout << '\n';
|
|
|
|
system("pause");
|
|
return 0;
|
|
}
|