String toInt and cut in pieces in a elegant way

For a remote control i need 4 unique, hardware generated long int numbers.
With the getIMEI() call in the MKRGSM i get the modems IMEI as a string.

My idea is to cut this string into 4 pieces and convert it to int.

Now i'm looking for elegant way to do this and here's the topic..;=)

So

String modems_IMEI;
modems_IMEI = bsgmodem.getIMEI();

For a unknown reason the getIMEI() is returning a string, example : "89410223701600158157"
Now i want to cut this in 4 pieces and save the result in a long unsigned int

something like toInt(),startposition, lenght would be nice :wink:
unsigned long foo1 = toInt(modems_IMEI),0,5

Any hints or ideas?

Thank you

Post your code. Read the forum guidelines to see how to properly post code and some information on how to get the most from this forum.
Use the IDE autoformat tool (ctrl-t or Tools, Auto format) before posting code in code tags.

Better? For two lines to explain and a fantasy wannahave function i thought it was not neccesary to convert...

String has numerous methods, perhaps substring() which is analogous to BASIC's mid$()

String() - Arduino Reference

may be something like this (if you insist on using the String class)

String IMEI = "89410223701600158157";

long extractIntFrom(String& source, size_t from, size_t to) { // to is exclusive
  char * endPtr;
  return strtol(source.substring(from, to).c_str(), &endPtr, 10); // you could use  endPtr to see if something went wrong
}

void setup() {
  Serial.begin(115200);
  Serial.println(extractIntFrom(IMEI, 0, 5));
  Serial.println(extractIntFrom(IMEI, 5, 10));
  Serial.println(extractIntFrom(IMEI, 10, 15));
  Serial.println(extractIntFrom(IMEI, 15, 20));
}

void loop() {}

the Serial monitor should show

89410
22370
16001
58157
1 Like

Nice. Thx. The MKRGSM lib insists on the String class, not me...

yeah, wish they had provided libraries not relying on dynamic memory allocation

Works like a charm. Elegantly.

I propose J-M-L's function

extractIntFromString(string, start_pos, end_pos)

to be part of the C standard lib!
Thx again :sunglasses:

strtol() is doing the magic and part of the standard library

Just need to pass the right parameters

If you don’t do error checking you can get rid of the pointer and just do


return strtol(source.substring(from, to).c_str(), nullptr, 10);

Have fun !

1 Like
unsigned long foo1 = modems_IMEI.substring(0,5).toInt();

(Note: .toInt() does actually return a long).

1 Like

That works too.

The reason I went for strtol() was to be able to actually be able to perform some error recovery but indeed if it's not used, sticking to the library (which does an atol()) is good enough

Also VERY nice! Thx

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.