【发布时间】:2017-01-10 19:42:45
【问题描述】:
我正在尝试读取 ANSI 格式的文件并将其转换为二进制文件。我正在声明两个动态内存分配,如下所示:char* binary_reverse = new char; 和 char * binary = new char;
调试时我看到这个(二进制)包含太多垃圾值。为什么会这样?
我正在删除这些,例如:delete binary_reverse;删除二进制; 然而,在删除它给我的错误:
'ASCIItoBinary.exe':已加载 'D:\TryingBest\Reactice\ASCIItoBinary\Debug\ASCIItoBinary.exe',已加载符号。 “ASCIItoBinary.exe”:已加载“C:\Windows\SysWOW64\ntdll.dll”,找不到或打开 PDB 文件 “ASCIItoBinary.exe”:已加载“C:\Windows\SysWOW64\kernel32.dll”,找不到或打开 PDB 文件 “ASCIItoBinary.exe”:已加载“C:\Windows\SysWOW64\KernelBase.dll”,找不到或打开 PDB 文件 “ASCIItoBinary.exe”:已加载“C:\Windows\SysWOW64\msvcr100d.dll”,已加载符号。 HEAP [ASCIItoBinary.exe]:00241ED0 处的堆块在 00241EFD 处修改,请求大小为 25 Windows 已在 ASCIItoBinary.exe 中触发断点。
我是这样写代码的:
#include <cstring>
void AtoB(char * input)
{
unsigned int ascii; //used to store ASCII number of a character
unsigned int length = strlen(input);
//cout << " ";
for (int x = 0; x < length; x++) //repeat until the input is read
{
ascii = input[x];
char* binary_reverse = new char; //dynamic memory allocation
char * binary = new char;
//char binary[8];
int y = 0;
while (ascii != 1)
{
if (ascii % 2 == 0) //if ascii is divisible by 2
{
binary_reverse[y] = '0'; //then put a zero
}
else if (ascii % 2 == 1) //if it isnt divisible by 2
{
binary_reverse[y] = '1'; //then put a 1
}
ascii /= 2; //find the quotient of ascii / 2
y++; //add 1 to y for next loop
}
if (ascii == 1) //when ascii is 1, we have to add 1 to the beginning
{
binary_reverse[y] = '1';
y++;
}
if (y < 8) //add zeros to the end of string if not 8 characters (1 byte)
{
for (; y < 8; y++) //add until binary_reverse[7] (8th element)
{
binary_reverse[y] = '0';
}
}
for (int z = 0; z < 8; z++) //our array is reversed. put the numbers in the rigth order (last comes first)
{
binary[z] = binary_reverse[7 - z];
}
//printf("the Binary is %s",binary);
//cout << binary; //display the 8 digit binary number
delete binary_reverse; //free the memory created by dynamic mem. allocation
delete binary;
}
}
我想要“二进制”中的确切二进制值。不是二进制值和垃圾?如何消除垃圾值?如何避免堆损坏?
【问题讨论】:
-
char* binary_reverse = new char;和char * binary = new char;- 所以你分配 1 个字节用于存储 -
题外话:节省一点代码:
else if (ascii % 2 == 1)可以是else。当处理单个二进制位时,它的值将是 1 或 0。如果不是一个,它必须是另一个。
标签: c++ windows visual-studio-2010