1

I need to create a string vector of MAC addresses from 1000.1111.1111 to 1000.1131.1111 or a range similar to that.

I am not sure how to increment the string, or if I concatenate then how to maintain leading zeros.

Any pointers are appreciated.

Yes these are hex. Although I would not mind a solution that takes care of base 10 only.

Bo Persson
  • 86,087
  • 31
  • 138
  • 198
AJ.
  • 2,506
  • 9
  • 43
  • 78
  • [This thread](http://stackoverflow.com/questions/5100718/int-to-hex-string-in-c) might be helpful. – Groo Jul 17 '12 at 07:21
  • @RedX: I believe OP meant, a range of 20000 mac addresses (although, it's actually 0x20000 addresses). – Groo Jul 17 '12 at 07:22
  • It seems that the number would fit in `unsigned long long`. Just convert starting number to `unsigned long long`, increment and convert back. – nhahtdh Jul 17 '12 at 07:26
  • Would you know how to generate a sequence of, say, 100 numbers? If yes, take each number and convert it to a hex string. Since MAC addresses are 48-bit wide, you can do it with three 16-bit integers, or a single 64-bit integer. – Groo Jul 17 '12 at 07:26
  • What is the output format you desire? Your example is somewhat "unusual". – Kerrek SB Jul 17 '12 at 07:35
  • Try [an implementation of next_combination][1] [1]: http://stackoverflow.com/questions/4436353/usage-of-this-next-combination-code – nurettin Jul 17 '12 at 07:40
  • Is this homework? It has classic edge case complexity introduced by there being more than 16565 addresses. – Peter Wood Jul 17 '12 at 09:42

1 Answers1

2

This will generate a vector of strings like this:

1000.1111.1111
1000.1111.1112
1000.1111.1113
<...>
1000.1112.1111
1000.1112.1112
<...>
1000.1131.1111

Code:

#include <iostream>
#include <string>
#include <sstream>

using namespace std;

//Converts a number (in this case, int) to a string
string convertInt(int number)
{
   stringstream ss;//create a stringstream
   ss << number;//add number to the stream
   return ss.str();//return a string with the contents of the stream
}

int main(int argc, char *argv[])
{
    //The result vector
    vector<string> result;
    string tmp;//The temporary item 
    for( int i = 1111; i < 1139; i++ )
        for( int j = 1111; j < 9999; j++ )
        {
            tmp = "1000.";//the base of the adress
            //Now we append the second and the third numbers.
            tmp.append( convertInt( i ) ).append( "." ).append( convertInt( j ) );
            //and add the tmp to the vector
            result.push_back(tmp);
        }
}
SingerOfTheFall
  • 27,171
  • 7
  • 60
  • 100