Problem with Long Variables

I am having an issue with long integers. I am using a Duemilanove board. I feel that I must have a setting wrong. I've pared it down to the most minimal. I am reading a string value from a file and want to operate on it as an unsigned long. In this example, the string in question is "0x00DC143C". Whenever I try to do anything with the top 16 bits, they are ignored.

#include <SPI.h>
#include <SD.h>
#define SIZEOF_HEXLONG 12

void setup() {
  // put your setup code here, to run once:
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  Serial.println("Initializing...");

  char pvBuffer1[SIZEOF_HEXLONG] = "0x00DC143C";
  char pvBuffer2[SIZEOF_HEXLONG] = "0x00DC";
  char pvBuffer3[SIZEOF_HEXLONG] = "0x143C";

  char buffer[60];
  Serial.print("Pixel String Input is: ");
  Serial.println(pvBuffer1);

  unsigned long PixelValue = (unsigned long)strtol(pvBuffer1,0,0);
  
  sprintf(buffer, "Full Char buffer PixelValue is 0x%08x!", PixelValue);
  Serial.println(buffer);

  unsigned long PixelValue2 = (unsigned long)strtol(pvBuffer2,0,0);
  unsigned long PixelValue3 = (unsigned long)strtol(pvBuffer3,0,0);

  sprintf(buffer, "Top Half PixelValue is 0x%08x!", PixelValue2);
  Serial.println(buffer);
  sprintf(buffer, "Bottom Half PixelValue is 0x%08x!", PixelValue3);
  Serial.println(buffer);

  unsigned long PixelValue4 = (unsigned long)((PixelValue2<<16) + PixelValue3);

  sprintf(buffer, "Merged PixelValue is 0x%08x!", PixelValue3);
  Serial.println(buffer);

}

void loop() {
  // put your main code here, to run repeatedly:

}```

This is the serial output:

Initializing...
Pixel String Input is: 0x00DC143C
Full Char buffer PixelValue is 0x0000143c!
Top Half PixelValue is 0x000000dc!
Bottom Half PixelValue is 0x0000143c!
Merged PixelValue is 0x0000143c!

I have come up with some ideas for work-arounds and am willing to buy a new board if I have to, but this seems like such an easy issue so it must be a configuration error or something.  Thank you in advance!

You forgot the the letter "l" in "lx".

  sprintf(buffer, "Full Char buffer PixelValue is 0x%08lx!", PixelValue);
2 Likes

Why don't you use strtoul() if you want to parse an unsigned long?

1 Like

Awesome! Thank you for saving my sanity! I guess 30+ years of ANSI C string formatting is no longer completely valid. :rofl:

New output:

Initializing...
Pixel String Input is: 0x00DC143C
Full Char buffer PixelValue is 0x00dc143c!
Top Half PixelValue is 0x000000dc!
Bottom Half PixelValue is 0x0000143c!
Merged PixelValue is 0x00dc143c!

When in doubt I always go to the reference library, e.g. printf - C++ Reference

It makes good sense to me that (s)printf() needs to know the length of the variable.

Great site cplusplus

Tom... :smiley: :+1: :coffee: :australia: