Reputation: 295
I made a converter which is supposed to work, and works in some cases, but in this case it doesn't work.
The problem is that when cout
ing the unsigned char
s generated, one time everything is 255, another time 0. What's wrong with this code??
Here's my code.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void longToBytes(long num, unsigned char arr[4])
{
arr[0]= (int)((num >> 24) & 0xFF);
arr[1]= (int)((num >> 16) & 0xFF);
arr[2]= (int)((num >> 8) & 0xFF);
arr[3]= (int)( num & 0xFF);
}
long bytesToLong(unsigned char arr[4])
{
return ((arr[0] << 24) + (arr[1] << 16) + (arr[2] << 8) + arr[3]);
}
void writelongs(long mas[], int howMany)
{
for(int i=0; i<howMany; i++)
{
unsigned char bytes[4];
cout<<mas[i]<<endl;
longToBytes(mas[i], bytes);
for(int j=0; j<4; j++)
{
cout<<(int)bytes[i]; //Problem here.
}
cout<<endl;
}
}
int main()
{
long aray[2]={-118, 1034};
writelongs(aray,2);
return 0;
}
Upvotes: 1
Views: 1602
Reputation: 22174
for(int j=0; j<4; j++)
{
cout<<(int)bytes[i]; // Problem here.
}
You used the index i instead of j.
for (int j = 0 ; j < 4 ; j++)
{
cout << (int)bytes[j]; // Problem solved.
}
Upvotes: 3