举例:一个TXT文本上有这样一些二进制数:
101000000000000000011010101 (最长64位)
101000000000101000000000010
000000000000001111110011001
-1(遇到-1时候输出)
输出: XXX
XXX
XXX
这个怎么做哦!我也不知道怎么能描述得更清楚点。反正你们看着办 帮帮我吧,有详细程序更好。呵呵~~~~~谢谢了 呵呵!
一个C++爱好者
string BinaryToHex(string BinaryStr)
{
string HexStr="0x";
int num=0;
int len=BinaryStr.length();
int start=0;
int end=len%4?len%4-1:3;
do
{
for(int i=start;i<=end;i++)
{
num+=(BinaryStr[start+end-i]-'0')*pow(2,i-start);
}
char buf[2];
itoa(num,buf,16);
HexStr+=buf;
num=0;
start=end+1;
end=start+3;
}while(start<len);
return HexStr;
}
void main()
{
ifstream ins("AAA.txt");
if(!ins)exit(1);
ofstream ous("BBB.txt");
if(!ous){
ins.close();
exit(1);
}
while(!ins.eof())
{
string str;
ins.getline(str,100);
if(str=="-1")break;
str=BinaryToHex(str);
ous<<str;
ous.put('\n');
}
ins.close();
ous.close();
}
[此贴子已经被作者于2007-3-28 13:52:36编辑过]
不要这样说.
先用一个string存储2进制数,然后得到长度len,判断他是不是4的倍数,如果是那么从0到3是第一个(2进制数转16进制数,因为2^4==16,所以是4位对应1位).如果不是(比如是11,那么11%4==3)所以第一个是3位数转换为16位(0到len%4-1),后面就是对齐后的了,都用4个2进制转换为1个16进制.
Example
/* ITOA.C: This program converts integers of various
* sizes to strings in various radixes.
*/
#include <stdlib.h>
#include <stdio.h>
void main( void )
{
char buffer[20];
int i = 3445;
long l = -344115L;
unsigned long ul = 1234567890UL;
_itoa( i, buffer, 10 );
printf( \"String of integer %d (radix 10): %s\n\", i, buffer );
_itoa( i, buffer, 16 );
printf( \"String of integer %d (radix 16): 0x%s\n\", i, buffer );
_itoa( i, buffer, 2 );
printf( \"String of integer %d (radix 2): %s\n\", i, buffer );
_ltoa( l, buffer, 16 );
printf( \"String of long int %ld (radix 16): 0x%s\n\", l,
buffer );
_ultoa( ul, buffer, 16 );
printf( \"String of unsigned long %lu (radix 16): 0x%s\n\", ul,
buffer );
}Output
String of integer 3445 (radix 10): 3445
String of integer 3445 (radix 16): 0xd75
String of integer 3445 (radix 2): 110101110101
String of long int -344115 (radix 16): 0xfffabfcd
String of unsigned long 1234567890 (radix 16): 0x499602d2