表格线识别通用库文档
载入中...
搜索中...
未找到
binary.hpp
浏览该文件的文档.
1/*
2 * @Description: 二进制工具函数 头文件及其实现
3 * @Version:
4 * @Autor: dreamy-xay
5 * @date: 2023-12-14
6 * @LastEditors: dreamy-xay
7 * @LastEditTime: 2024-03-13
8 */
9
10#ifndef COMMON_UTILS_BINARY_HPP
11#define COMMON_UTILS_BINARY_HPP
12
13#include <vector>
14
15#include "common/enum.h"
16#include "common/macro.h"
17#include "common/type.h"
18
19/* declare */
20namespace cm {
21
22bool ReadBit(uint number, ushort bit);
23uint WriteBit(uint number, ushort bit, bool value);
24
25std::vector<byte> IntToBytes(uint number, bool big_endian = true);
26uint BytesToInt(const std::vector<byte>& bytes, bool big_endian = true);
27
28} // namespace cm
29
30/* implement */
31namespace cm {
32
49inline bool ReadBit(uint number, ushort bit) {
50 return number >> bit & 1;
51}
52
68inline uint WriteBit(uint number, ushort bit, bool value) {
69 // 将第 bit 位设置为 1,或者设置为 0
70 return value ? number | (1u << bit) : number & ~(1u << bit);
71}
72
88inline std::vector<byte> IntToBytes(uint number, bool big_endian) {
89 std::vector<byte> bytes;
90
91 if (big_endian)
92 for (int i = sizeof(number) - 1; i >= 0; --i)
93 bytes.emplace_back((number >> (8 * i)) & 0xFF);
94 else
95 for (int i = 0; i < sizeof(number); ++i)
96 bytes.emplace_back((number >> (8 * i)) & 0xFF);
97
98 return std::move(bytes);
99}
100
116inline uint BytesToInt(const std::vector<byte>& bytes, bool big_endian) {
117 uint number = 0;
118
119 // 字节数
120 std::size_t num_bytes = bytes.size();
121
122 if (big_endian)
123 for (size_t i = 0; i < num_bytes; ++i)
124 number = (number << 8) | bytes[i];
125 else
126 for (size_t i = num_bytes; i > 0; --i)
127 number = (number << 8) | bytes[i - 1];
128
129 return number;
130}
131
132} // namespace cm
133
134#endif
点类
Definition point.hpp:52
unsigned int uint
无符号整型
Definition type.h:22
std::vector< byte > IntToBytes(uint number, bool big_endian=true)
将整数转换为字节数组
Definition binary.hpp:88
uint BytesToInt(const std::vector< byte > &bytes, bool big_endian=true)
将字节数组转换为整数
Definition binary.hpp:116
unsigned short ushort
无符号短整型
Definition type.h:28
uint WriteBit(uint number, ushort bit, bool value)
设置数字中特定位的值
Definition binary.hpp:68
bool ReadBit(uint number, ushort bit)
读取数字中特定位的值
Definition binary.hpp:49