Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
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

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

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;
}

![]() |
![]() |
![]() |

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