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
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
J-M-L
March 18, 2022, 5:49pm
5
intstarep:
Any hints or ideas?
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...
J-M-L
March 18, 2022, 5:56pm
7
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
J-M-L
March 19, 2022, 8:49am
9
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
PaulRB
March 19, 2022, 9:26am
10
unsigned long foo1 = modems_IMEI.substring(0,5).toInt();
(Note: .toInt()
does actually return a long).
1 Like
J-M-L
March 19, 2022, 1:14pm
11
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
system
Closed
September 15, 2022, 3:03pm
13
This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.