c++中如何输出字符串的ASCII码

要在C++中输出一个字符串的ASCII码,比如说hello,要输出的结果为:
0110 1000
0110 0101
0110 1100
0110 1100
0110 1111
五个二进制结果。
急,在线=。先奉上30分,好的话追加50,多谢了

第1个回答  2009-06-19
#include <iostream.h>
#include <stdlib.h>

void asc2bin(int ch)
{
int i, a[8];

for (i = 0; i < 8; ++i)
{
a[8 - i - 1] = ch % 2;
ch /= 2;
}

for (i = 0; i < 8; ++i)
{
cout << a[i];

if ((i + 1) % 4 == 0)
cout << ' ';
}
}

void main()
{
char str[100];
int i = 0;

cout << "Please input a string: " << endl;
cin.getline(str, 100);

while (str[i])
{
asc2bin(str[i++]);
cout << endl;
}

system("PAUSE");
}
第2个回答  2009-06-19
#include <stdio.h>

int main()
{
int a;
int i;
int n;
char str[20];
char* str1=str;
printf("请输入一个字符串:\n");
gets(str);
while(*str1!='\0')
{
a=*str1;
n=0x80;
for(i=0;i<8;i++)
{
printf("%d",a&n?1:0);
n>>=1;
}
printf("\n");
str1++;
}
}

C++
#include <iostream.h>

int main()
{
int a;
int i;
int n;
char str[20];
char* str1=str;
cout<<"请输入一个字符串:"<<endl;
cin>>str;
while(*str1!='\0')
{
a=*str1;
n=0x80;
for(i=0;i<8;i++)
{
cout<<(a&n?1:0);
n>>=1;
}
cout<<endl;
str1++;
}
}
第3个回答  2009-06-21
#include <iostream>
#include <cmath>
using namespace std;
int Change(int s) //把十进制转为二进制
{
int t = 0;
int count = 0;
while(s != 0)
{
int tmp = s % 2;
t += tmp * pow(10, count++);
s = s / 2;
}
return t;
}
int main(int argc, char* argv[])
{
char s1[100];
int s2[100];
cout<<"请输入字符串"<<endl;
cin>>s1;
int i=0;
while(s1[i]!='\0') //把字符转为ASCII码
{
s2[i]=s1[i];
i++;
}

int k=0;
do
{
cout<<Change(s2[k])<<endl;
k++;
}while(k<i);

return 0;
}
第4个回答  2009-06-19
#include <iostream>
using namespace std;
int main()
{

char h[1000];
char a[1000][1000];
cout<<"请输入你要转换为ASCII码的字符串:"<<endl;
cin>>h;

for(int i=0;i<strlen(h);i++)
{
int b=int(h[i]);
itoa(b,a[i],2);
cout<<a[i]<<endl;
}
}
第5个回答  2009-06-19
这个简单. 等着.

#include<iostream>
using namespace std;

void tentotwo(char c)
{
if(c/2 != 0)
tentotwo(c/2);
else
printf("%d",c/2);
printf("%d",c%2);
}

int main()
{
char s[100];
int i=0;
gets(s);

while(s[i]!='\0')
{
tentotwo(s[i]);
putchar('\n');
i++;
}
return 0;
}本回答被提问者采纳
相似回答