Computing.Net > Forums > Programming > Convert int to Char c++

Computer Problems? Computing.Net has over 1,000,000 posts about all things technology related! Over 90% answered within 24 hours! Click here to start participating now! Also, be sure to check out the New User Guide.

Convert int to Char c++

Reply to Message Icon

Name: Skips
Date: April 7, 2005 at 14:50:33 Pacific
OS: XP SP1a
CPU/Ram: AMD 1.8Ghz
Comment:

I have a program which im writing that will count up ip addresses starting from 1.0.0.1. Each octet of the ip address is assigned as an int.

ie int oct1, int oct2

I then want to assign these 4 values to make one address which is assigned as a char.

My program keeps telling my cannot convert int to char.

Any ideas?
Cheers




Sponsored Link
Ads by Google

Response Number 1
Name: Skips
Date: April 7, 2005 at 14:52:11 Pacific
Reply:

To add:

I know you can use sprintf to print it, but im not actually wanting to print it.


0

Response Number 2
Name: StuartS
Date: April 7, 2005 at 15:25:04 Pacific
Reply:

Char is 8 bits. Int is 16 bits. Therefore you cannot get 16 bits into 8 bits without data overflow.

So why not use Char to begin with. A char can have maximum value of 255 which is all you need for an IP octet.

The full IPA address is 32 bits which needs a Long Int. You can put 4 char data types into a Long Int.

Alternatively just use a Long Int and use bit masking to isolate the four octets.

Stuart


0

Response Number 3
Name: SteveCary55
Date: May 4, 2005 at 22:56:18 Pacific
Reply:

try this out...sprintf doesn't print to an output device, it alters a variable. This made my laptop screen get all frizzy when it was running...it's not my fault if you blow something up.
I made cout print to the screen so you could see what was going in...replace that with what you want to do with the ipAddress variable.


#include <iostream>
using namespace std;

int main()
{
char ipAddress[16] = " ";
int oct1 = 1;
int oct2 = 0;
int oct3 = 0;
int oct4 = 1;

while (oct1 <= 255)
{
while (oct2 <= 255)
{
while (oct3 <= 255)
{
while (oct4 <= 255)
{
sprintf(ipAddress, "%d.%d.%d.%d", oct1, oct2, oct3, oct4);
cout << endl << ipAddress;
oct4++;
}
oct3++;
oct4 = 0;
}
oct2++;
oct3 = 0;
}
oct1++;
oct2 = 0;
}

cin.get();
cin.get();
return 0;
}


0

Sponsored Link
Ads by Google
Reply to Message Icon

Related Posts

See More







Post Locked

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.


Go to Programming Forum Home


Sponsored links

Ads by Google


Results for: Convert int to Char c++

Converting int to char www.computing.net/answers/programming/converting-int-to-char/6800.html

Converting int to char* www.computing.net/answers/programming/converting-int-to-char/10546.html

convert void* to char www.computing.net/answers/programming/convert-void-to-char-/16145.html