尝试将二进制数组转换为十六进制C++然后打印结果

Trying to convert C++ binary array to hexadecimal then print results

本文关键字:C++ 十六进制 然后 打印 结果 转换 二进制 数组      更新时间:2023-10-16

我想打印一个 8 字节的 int 数组,并将其转换为 bin 和十六进制,输出如下:

0 00000000 00
1 00000001 07
...

我已经完成了二进制转换函数的创建。我想使用与二进制转换相同的函数 - 带有数组,但用右半部分检查左半部分并解决 8 个字节的每个不同方面;最左边的-3和最右边的-7。 我做错了什么?我不知道如何实现它,我知道我的十六进制函数都很古怪。

#include <iostream>
#include <string>
#include <math.h>
using namespace std;
const int num = 8; //may not be needed -added for hex
void Generatebinary(int arr[]);
void GeneratehexDec(int arr[]);
void print_binary(int arr[]); //haven't created yet
int main()
{
int arr[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
int i = 1;
while (i < 256)
{
Generatebinary(arr);
print_binary(arr); //not created yet
GeneratehexDec(arr);
i++;
}
}
void Generatebinary(int arr[])
{
for (int i = 7; i > 0; i--)
{
if (arr[i] == 1)
arr[i] = 0;
else if (arr[i] == 0)
{
arr[i] = 1;
break;
}
}
}
void GereatehexDec(int num)
{ //improper use
int a;
int i;
int answer[] = { };
a = num % 16;
i++;
answer[i] = num;
for (int i = num; i > 0; i--)
{
cout << answer[i];
}
cout << a;
}

首先,你不能做int answer[] = { };数组必须预先分配(指示它将存储多少元素)或必须在运行时动态分配,然后被释放,你必须管理你的内存,不要忘记解除分配......正是出于这个原因,Stroustrup告诉你除非必要,否则不要使用数组。使用 std::vector

void GereatehexDec(int num)
{ //improper use
int a = 0; // always initialize your variables
int i = 0; // is this i supposed to be the same as the i in the for loop below?
std::vector<int> answer;
a = num % 16;
i++; // this doesn't make sense
answer.at(i) = num;
for (int i = num; i > 0; i--) // what about the i variable you declared previously?
{
cout << answer.at(i);
}
cout << a;
}

这是一个可以帮助您的模板函数(将数字转换为字符串十六进制)

template <typename I> std::string n2hexstr(I w, size_t hex_len = sizeof(I) << 1) {
static const char* digits = "0123456789ABCDEF";
std::string rc(hex_len, '0');
for (size_t i = 0, j = (hex_len - 1) * 4; i<hex_len; ++i, j -= 4)
rc[i] = digits[(w >> j) & 0x0f];
return "0x" + rc;
}
int main() {
std::cout << n2hexstr(127);
}