C语言中,字符串怎么转换为int数组?

例如传入的是"01020304",

转换得到{0x01, 0x02, 0x03, 0x04}
之后再转换回"01020304"
这两个转换怎么做?还是不能做?

#include<stdio.h>
#include<math.h>
#include<string.h>
#include<conio.h>
void main(){
 int exc_n(char ch[]);int pnum=0;
 do{//套用了我之前写的一个转换函数,输出有点勉强。。。(固定输出头0x0...) 
  char ch[10]={0};char spr[2]={0};//分隔输入
 printf("input the string of num.\n不得不说下,每次输入一个数据,按'x'可以结束程序\n");
 scanf("%s",&ch);
 printf("0x0%x\n",pnum=exc_n(ch));
 //printf("%x",pnum);
 }while(getch()!='x');
}

//该函数将字符串型数字与整型数字单向转换
int exc_n(char ch[]){//,long lnum){
 int size=0;int num=0;
 if(sizeof(ch[0])>0)
   size=strlen(ch);int i=0;
   while(size>=0){
    if(ch[size]>47&&ch[size]<58){num=num+(ch[size]-48)*(int)pow(10,i++);
    }
    size--;
    //
   }
   return num;
}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2014-11-07
你这是转换为16进制数啊
不过是可以实现的,好在我之前做过,代码在此:

int str16toint(char s[])
{
int i,m,temp=0,n;
m=strlen(s);//十六进制是按字符串传进来的,所以要获得他的长度
for(i=0;i<m;i++)
{
if(s[i]>='A'&&s[i]<='F')//十六进制还要判断他是不是在A-F或者a-f之间a=10。。
n=s[i]-'A'+10;
else if(s[i]>='a'&&s[i]<='f')
n=s[i]-'a'+10;
else n=s[i]-'0';
temp=temp*16+n;
}
return temp;
}

void HextoStr( const char *sSrc, char *sDest, int nSrcLen )
{
int i;
char szTmp[3];

for( i = 0; i < nSrcLen; i++ )
{
sprintf( szTmp, "%02X", (unsigned char) sSrc[i] );
memcpy( &sDest[i * 2], szTmp, 2 );
}
return ;
}

void HexStrToByte(const char* source, unsigned char* dest, int sourceLen)
{
short i;
unsigned char highByte, lowByte;

for (i = 0; i < sourceLen; i += 2)
{
highByte = toupper(source[i]);
lowByte = toupper(source[i + 1]);

if (highByte > 0x39)
highByte -= 0x37;
else
highByte -= 0x30;

if (lowByte > 0x39)
lowByte -= 0x37;
else
lowByte -= 0x30;

dest[i / 2] = (highByte << 4) | lowByte;
}
return ;
}追问

怎么调用呢?举个例子吧,配上参数,谢谢。另外程序报错error C2065: 'toupper' : undeclared identifier

追答

toupper()函数的作用是把小写的字母转化为大写,要用这个函数的话要加入相应的头文件
#include

本回答被网友采纳
第2个回答  2017-06-02
String s = "485729304";

int[] a = new int[s.length()];
for(int i = 0; i < s.length(); i++)
{
//先由字符串转换成char,再转换成String,然后Integer

a[i] = Integer.parseInt( String.valueOf(s.charAt(i)));

}
//字符串中的数据一定要是数字,否则会出现异常
s.charAt(i);得到字符串i位置的值,
String.valueOf(); 转换char类型为字符串
Integer.parseInt();由String转换成Integer
第3个回答  2017-06-19
用ASCII码,例如
char s[] = "12345";
int c = s[2];
则c的值就是3,因为0~9的ASCII码与其本身所代表的的数字相同
第4个回答  2017-06-02

词频统计吗?

不需要对齐字典数组吗?

//对于下列字符:
String str = "hello";

//输出这种格式吗?:{"h":1,"e":1,"l":2,"o":1}
//还是这种?:[1,1,2,1]

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网