Find largest element in a type

Is there a function to find the largest element in a type?

e.g.
highfunction(uint16_t) --> 65536

or
uint16_t i;
highfunction(i) --> 65536

Predefined constants would help too.

rsardu:
Is there a function to find the largest element in a type?

e.g.
highfunction(uint16_t) --> 65536

or
uint16_t i;
highfunction(i) --> 65536

Predefined constants would help too.

Not that I know of. FYI, unsigned 16 bit int is 65535. You can use the calculator on your PC to check these.

Try: <cstdint> (stdint.h) - C++ Reference

On any board except AVR, you can use [

std::numeric_limits

](std::numeric_limits - cppreference.com), which is the standard way of doing this in C++.
On AVR, you’ll have to use the C macros like UINT[i]N[/i]_MAX or a third-party port of the standard library.

#include <limits>

void setup() {
  Serial.begin(115200);
  while (!Serial);
  Serial.println(std::numeric_limits<uint16_t>::max()); // prints 65535
}

void loop() {}

Pieter

Or good old limits.h, see C Library - <limits.h> - Tutorialspoint

# include <limits.h>

void setup() {
	Serial.begin(9600);
	
	int y = SCHAR_MIN;
	Serial.println(y);
}

void loop() {

}

HTH

a7

Sketch of Post#3 is not compiled. The error message is:

sketch_mar17b:6:53: error: macro “max” requires 2 arguments, but only 1 given

Serial.println(std::numeric_limits<uint16_t>::max()); // prints 65535

I did compile it. It works correctly for the Nano 33 BLE.
Did you compile it for AVR?

PieterP:
I did compile it. It works correctly for the Nano 33 BLE.
Did you compile it for AVR?

I have compilation error for both "Arduino UNO" and "Arduino NANO with Old Bootloader option".

GolamMostafa:
I have compilation error for both "Arduino UNO" and "Arduino NANO with Old Bootloader option".

Did you read my post?

PieterP:
On any board except AVR, you can use [

std::numeric_limits

](std::numeric_limits - cppreference.com), which is the standard way of doing this in C++.
On AVR, you'll have to use the C macros like UINT[i]N[/i]_MAX or a third-party port of the standard library.

Something like ui = 2^32 seems not to work.

rsardu:
Something like ui = 2^32 seems not to work.

That’s not a portable solution, and you’re using an XOR operator, not exponentiation: Arithmetic operators - cppreference.com

An unsigned integer of width N can't hold a value of 2^N (where '^' is to be taken as exponentiation).

What you are calling an "element" is really called a "value".

std::numeric_limits<uint16_t>::max()

verses

UINT16_MAX

I guess “Modern C++” programmers are paid by the character :smiley:

void setup() {
  SerialUSB.begin(9600);
}
void loop() {
  uint64_t i;
  i = UINT32_MAX + uint64_t(1);
  SerialUSB.println(i);
}

Works. Thanks!

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