Long int to char

I am using a generic door/window sensor with this code and I get a sensor id value of 5592405.

#include <RCSwitch.h>

RCSwitch sensorSwitch = RCSwitch();

void setup()
  {
    sensorSwitch.enableReceive(0);  // Receive on interrupt 0 => that is pin #2
  }

void loop()
  {
    //RC Switch
    if (sensorSwitch.available()) {
      long sensor = sensorSwitch.getReceivedValue();
      }
  sensorSwitch.resetAvailable();
  }

I need to strcat() the sensor id to a char array, so need to convert it.
From searching c++ forums I found a suggested a solution as implemented in the partial below code with sensor declared as : char sensor[10];.
The conversion works, but the sensor id value changes to 21845.

if (sensorSwitch.available()) {
      long sensor1 = sensorSwitch.getReceivedValue();
      sprintf(sensor,"%d", sensor1);
      if (sensor1 > 1) Rx = true;
      }

Appreciate if someone could give me correct solution.

 sprintf(sensor,"%ld", sensor1);

Thanks AWOL - that fixed the problem.

Is that the most efficient method to use for converting in terms of using resources?

From previous tests I did sprintf() is quite resource hungry.

I don't know what's most efficient, but the first question I'd ask is "why are you converting to decimal ASCII?"
It's often simpler and quicker, if it has to be converted to ASCII, to represent the number in hex.

AWOL:
I don't know what's most efficient, but the first question I'd ask is "why are you converting to decimal ASCII?"
It's often simpler and quicker, if it has to be converted to ASCII, to represent the number in hex.

The sensor id value is concatenated to an array as part of a "POST" request which is posted to an online database. The values in the database in turn are displayed on a web page.

aisc:
Thanks AWOL - that fixed the problem.

Is that the most efficient method to use for converting in terms of using resources?

From previous tests I did sprintf() is quite resource hungry.

Is itoa() less resource hungry. Also not sure if int here means 16 or 32 bit as this varies between implementations.

itoa() is less resource hungry, but the compiler complains.
Note this test was done with int and not with long.

int a = 99;
char b[10];

void setup() {
  Serial.begin(9600);
  while(!Serial);

  itoa ( a, b, 10 );
//  sprintf(b, "%d", a);
  Serial.print("a = ");
  Serial.println(a);
  Serial.print("b = ");
  Serial.println(b);

}

void loop() {
}

Sketch uses 2,358 bytes (7%) of program storage space. Maximum is 32,256 bytes.
Global variables use 222 bytes (10%) of dynamic memory, leaving 1,826 bytes for local variables. Maximum is 2,048 bytes.

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at javax.swing.text.ParagraphView.getClosestPositionTo(ParagraphView.java:274)
at javax.swing.text.ParagraphView.getNextNorthSouthVisualPositionFrom(ParagraphView.java:241)
at javax.swing.text.CompositeView.getNextVisualPositionFrom(CompositeView.java:476)
at javax.swing.text.Utilities.getNextVisualPositionFrom(Utilities.java:1045)
at javax.swing.text.CompositeView.getNextNorthSouthVisualPositionFrom(CompositeView.java:726)
at javax.swing.text.CompositeView.getNextVisualPositionFrom(CompositeView.java:476)
at javax.swing.plaf.basic.BasicTextUI$RootView.getNextVisualPositionFrom(BasicTextUI.java:1588)
at javax.swing.plaf.basic.BasicTextUI.getNextVisualPositionFrom(BasicTextUI.java:1127)
at javax.swing.text.DefaultEditorKit$NextVisualPositionAction.actionPerformed

.... and a lot more

int a = 99;
char b[10];

void setup() {
  Serial.begin(9600);
  while(!Serial);

//  itoa ( a, b, 10 );
  sprintf(b, "%d", a);
  Serial.print("a = ");
  Serial.println(a);
  Serial.print("b = ");
  Serial.println(b);

}

void loop() {
}

Sketch uses 3,722 bytes (11%) of program storage space. Maximum is 32,256 bytes.
Global variables use 224 bytes (10%) of dynamic memory, leaving 1,824 bytes for local variables. Maximum is 2,048 bytes.

Edit : Re-compiled itoa() several times with no complaints from compiler, so might just have been a glitch.

Results with long.

itoa() uses same resources for int and long.
sprint() uses more resources for long than int.

long itoa():
Sketch uses 2,358 bytes (7%) of program storage space. Maximum is 32,256 bytes.
Global variables use 222 bytes (10%) of dynamic memory, leaving 1,826 bytes for local variables. Maximum is 2,048 bytes.

long sprintf():
Sketch uses 3,724 bytes (11%) of program storage space. Maximum is 32,256 bytes.
Global variables use 226 bytes (11%) of dynamic memory, leaving 1,822 bytes for local variables. Maximum is 2,048 bytes.

Code Used:

int a = 99888777;
char b[10];

void setup() {
  Serial.begin(9600);
  while(!Serial);

  itoa ( a, b, 10 );
  sprintf(b, "%ld", a);
  Serial.print("a = ");
  Serial.println(a);
  Serial.print("b = ");
  Serial.println(b);

}

void loop() {
}

A follow-on question.

char * itoa ( int value, char * str, int base );

Convert integer to string (non-standard function)

Converts an integer value to a null-terminated string using the specified base and stores the result in the array given by str parameter.

What kind of string does sprint() return? Is it null terminated or does the null termination have to be explicitly added?

Guess I can go search for that...

Found it - great link Riva, will have to bookmark it :slight_smile:

int sprintf ( char * str, const char * format, ... );

Write formatted data to string

Composes a string with the same text that would be printed if format was used on printf, but instead of being printed, the content is stored as a C string in the buffer pointed by str.

The size of the buffer should be large enough to contain the entire resulting string (see snprintf for a safer version).

A terminating null character is automatically appended after the content.

After the format parameter, the function expects at least as many additional arguments as needed for format.

sprintf returns the number of characters it wrote into the supplied buffer, but that count doesn't include the null terminator it also wrote.

@AWOL : Noted - thanks.

@Riva : I have changed my sketch to use itoa() and freed up 5% of flash and a few tidbits of SRAM.

Using sprintf():
Sketch uses 24,256 bytes (75%) of program storage space. Maximum is 32,256 bytes.
Global variables use 1,489 bytes (72%) of dynamic memory, leaving 559 bytes for local variables. Maximum is 2,048 bytes.

Using itoa():
Sketch uses 22,884 bytes (70%) of program storage space. Maximum is 32,256 bytes.
Global variables use 1,485 bytes (72%) of dynamic memory, leaving 563 bytes for local variables. Maximum is 2,048 bytes.

This line:

sensor[strlen(sensor)] = '\0';

is completely unnnecessary. sprintf null terminates the string. And, if it didn't, strlen would not work, so this line would not work anyway.

Regards,
Ray L.

RayLivingston:
This line:

sensor[strlen(sensor)] = '\0';

is completely unnnecessary. sprintf null terminates the string. And, if it didn't, strlen would not work, so this line would not work anyway.

Regards,
Ray L.

Hmmm, if you reread the thread, you will note that earlier in the thread I addressed that issue.

Oops - Correction: itoa() does not work with a long integer!

When I ran the original test code I only ran it once with both functions uncommented and since sprintf() was the second one, the answer displayed correctly.

To get the memory usage, I only compiled with each function uncommented in turn.

Revised test code :

long a = 99888777;

void setup() {
  Serial.begin(9600);
  while(!Serial);

  Serial.print("a = ");
  Serial.println(a);

  char b[10];
  itoa ( a, b, 10 );
  Serial.print("b = ");
  Serial.println(b);
  
  char c[10];
  sprintf(c, "%ld", a);
  Serial.print("c = ");
  Serial.println(c);

}

void loop() {
}

I can find atol(), but not the reverse.

I can find atol(), but not the reverse.

ltoa ()

AWOL:
ltoa ()

Well well well what do u know....

I assumed I needed ltoa() but when I did a search for it on the c++ ref site, the search returned itoa()!
I also looked through the list of functions and did not see it anywhere so I assumed it did not exist - hmmm.... puzzled :(.

Anyway tested in the IDE and it works.
Thanks AWOL.

I agree with the general notion that sprintf() is an H-bomb-to-kill-an-ant in most cases. The reason is because most programs only use a small part of its functionality. In a small test program:

void setup()
{
  char str[9];
  long val = 5592405;

  Serial.begin(9600);
 // sprintf(str, "%ld", val);       // Toggle these two lines for the test
  ltoa(val, str, 10);               // And this one
  Serial.println(str);
}

void loop()
{
}

the sprintf() version used 3318 bytes and the ltoa() version used 1976 bytes. Unless you are doing multiple conversions using different data types, sprintf() is going to bloat your code more than the alternatives.

A silly thought but is there a way to use the .print class to do the conversion to a char string for you. There might be very little overhead then if your already using Serial (or some other library that implements the .print class).

I was looking for something else, when I noted this.

I tested it with this :

  int x = 5;
  char u = char(x);
  Serial.print("u = ");
  Serial.println(u);

but drew a blank.

The reference page did not have an example.
How should this the char() function be used?

No. This char() function is simply a cast. You now have the '\0x05' character, the character with the value 5.

You just need to do this:
char u = x+'0';