problem in array assigment

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
using namespace std;
main(){
       char datan[8]={'0','0','6','0','7','b','4','5'};
       unsigned char data[4]={0};
                data[0]=(datan[0]<<4)+datan[1];
                data[1]=(datan[2]<<4)+datan[3];
                data[2]=(datan[4]<<4)+datan[5];
                data[3]=(datan[6]<<4)+datan[7];
                
  	            cout<<datan<<","<<data<<endl;
  	                
  	            system("pause");        
}


the output is

D:\Dev-Cpp>testdata
00607b45?",0愐u00607b45?"

should it be the same?


what is the resean?
Last edited on
It's not the same. simply you dont have \0 at the end of your arrays so they are printed until cout finds one. original array is '00607b45 then' , '?"' is rubbish, then , then '0愐u' is what you created, and '00607b45?"' is there because in your memory datan goes after data.
thank you very much.


but I use printf("%2x%2x%2x%2x\n",data[0],data[1],data[2],data[3]) ;

the output is
3090d275


shouldn't it be 00607b45?

how can I get the right values?

I don't understand why a 4-length character array contains "0愐u00607b45?",it is too long ,isn't it?
Your printing two hex digits here.
'0' is not the same as 0
'0' in fact == 48. dec 48 == hex 30, so you get 30.
so complicate
I only want to convert a string of hex meaning of 00607b45 to {0x00,0x60,0x7b,0x45}

would you give me a easy way?
how about
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
using namespace std;
main(){
       char datan[4]={0x00,0x60,0x7b,0x45};
       unsigned char data[4]={0};
                data[0]=(datan[0]<<4)+datan[1];
                data[1]=(datan[2]<<4)+datan[3];
                data[2]=(datan[4]<<4)+datan[5];
                data[3]=(datan[6]<<4)+datan[7];
                
                  cout<<datan<<","<<data<<endl;//this wont work here
                  cout << hex;
                  for(int i = 0; i < 4; i++) cout << (int)datan[i]
                  cout.put(',');
                  for(int i = 0; i < 4; i++) cout << (int)data[i]
                      
                  system("pause");  //http://www.cplusplus.com/forum/articles/11153/
       cin.get();      
}
Last edited on
Topic archived. No new replies allowed.