【40】C++实战篇——有符号整数转换为十六进制,按小端序(LSB, Least Significant Byte first)存储在内存中的规则,及代码实现
·
1. 问题描述
有符号整数转换为十六进制,按小端序(LSB, Least Significant Byte first)存储在内存中的规则。
示例如下:
Signed Integer, LSB
Example 1 (DX1=-2024) : Dec: -2024, Hex: 0xFFFFF818
- 0x404: 18
- 0x405: F8
- 0x406: FF
- 0x407: FF
Example 2 (DX1=20):
Dec: 20, Hex: 0x00000014
0x404: 14
0x405: 00
0x406: 00
0x407: 00
这段编码是关于将带符号的整数转换为十六进制,并且按小端序(LSB, Least Significant Byte first)存储在内存中的规则。具体来说,它展示了如何将一个带符号的整数转换为十六进制表示,并按字节顺序存储在连续的内存地址中。
-
1.带符号整数转换为十六进制表示:
- 正数直接转换为十六进制表示。
** 负数则先按其绝对值转换为十六进制表示,然后对结果取补码。
- 正数直接转换为十六进制表示。
-
2.小端序存储(Little Endian):
- 在小端序中,较低有效位(LSB)的字节存储在内存中较低的地址上,而较高有效位(MSB)的字节存储在内存中较高的地址上。
具体示例:
示例 1:DX1 = -2024
- 1.十进制表示: -2024
- 2.转换为十六进制表示:
- 先将绝对值2024转换为十六进制:2024 = 0x07E8
- 对0x07E8取补码:0xFFFFF818
- 3.按小端序存储:
- 0xFFFFF818 分别拆分为 18, F8, FF, FF 存储在内存地址0x404到0x407。
- 0x404: 18
- 0x405: F8
- 0x406: FF
- 0x407: FF
示例 2:DX1 = 20
- 1.十进制表示: 20
- 2.转换为十六进制表示:
- 20 转换为十六进制:20 = 0x14
- 因为是正数,直接使用其十六进制表示0x00000014。
- 3.按小端序存储:
- 0x00000014 分别拆分为 14, 00, 00, 00 存储在内存地址0x404到0x407。
- 0x404: 14
- 0x405: 00
- 0x406: 00
- 0x407: 00
总的来说,这段编码展示了如何将带符号整数转换为十六进制表示,并按小端序存储在内存中的具体方法。
2 代码实现
#include <iostream>
#include <iomanip>
#include <cstdint>
// 将有符号整数转换为十六进制并按字节输出
void convertAndPrint(int32_t value, uint8_t bytes[4]) {
uint32_t hexValue = static_cast<uint32_t>(value); // 转换为无符号整数以处理负数的二补数表示
// 分解为4个字节,按LSB顺序存储
bytes[0] = static_cast<uint8_t>(hexValue & 0xFF);
bytes[1] = static_cast<uint8_t>((hexValue >> 8) & 0xFF);
bytes[2] = static_cast<uint8_t>((hexValue >> 16) & 0xFF);
bytes[3] = static_cast<uint8_t>((hexValue >> 24) & 0xFF);
// 输出结果
std::cout << "Dec: " << value << ", Hex: 0x" << std::hex << std::setw(8) << std::setfill('0') << hexValue << std::dec << std::endl;
std::cout << "- 0x404: " << std::hex << std::setw(2) << std::setfill('0') << static_cast<int>(bytes[0]) << std::endl;
std::cout << "- 0x405: " << std::hex << std::setw(2) << std::setfill('0') << static_cast<int>(bytes[1]) << std::endl;
std::cout << "- 0x406: " << std::hex << std::setw(2) << std::setfill('0') << static_cast<int>(bytes[2]) << std::endl;
std::cout << "- 0x407: " << std::hex << std::setw(2) << std::setfill('0') << static_cast<int>(bytes[3]) << std::endl;
}
int main() {
int32_t example1 = -2024;
int32_t example2 = 20;
uint8_t bytes[4];
std::cout << "Example 1 (DX1=-2024):" << std::endl;
convertAndPrint(example1, bytes);
std::cout << "\nExample 2 (DX1=20):" << std::endl;
convertAndPrint(example2, bytes);
return 0;
}

更多推荐

所有评论(0)