Dart int toUnsigned()
Syntax & Examples

int.toUnsigned() method

The `toUnsigned` method in Dart returns the least significant width bits of this integer as a non-negative number (i.e., unsigned representation).


Syntax of int.toUnsigned()

The syntax of int.toUnsigned() method is:

 int toUnsigned(int width) 

This toUnsigned() method of int returns the least significant width bits of this integer as a non-negative number (i.e. unsigned representation). The returned value has zeros in all bit positions higher than width.

Parameters

ParameterOptional/RequiredDescription
widthrequiredThe number of bits to keep.

Return Type

int.toUnsigned() returns value of type int.



✐ Examples

1 Convert an integer to unsigned with a smaller width

In this example,

  1. We assign the value 5 to the integer variable num1 and specify width1 as 4.
  2. We convert num1 to an unsigned value with width1 using the toUnsigned() method.
  3. We print the result to standard output.

Dart Program

void main() {
  int num1 = 5;
  int width1 = 4;
  int unsignedValue1 = num1.toUnsigned(width1);
  print('Unsigned value of $num1 with width $width1: $unsignedValue1');
}

Output

Unsigned value of 5 with width 4: 5

2 Convert a negative integer to unsigned with a larger width

In this example,

  1. We assign the value -3 to the integer variable num2 and specify width2 as 6.
  2. We convert num2 to an unsigned value with width2 using the toUnsigned() method.
  3. We print the result to standard output.

Dart Program

void main() {
  int num2 = -3;
  int width2 = 6;
  int unsignedValue2 = num2.toUnsigned(width2);
  print('Unsigned value of $num2 with width $width2: $unsignedValue2');
}

Output

Unsigned value of -3 with width 6: 61

3 Convert a positive integer to unsigned with a smaller width

In this example,

  1. We assign the value 10 to the integer variable num3 and specify width3 as 3.
  2. We convert num3 to an unsigned value with width3 using the toUnsigned() method.
  3. We print the result to standard output.

Dart Program

void main() {
  int num3 = 10;
  int width3 = 3;
  int unsignedValue3 = num3.toUnsigned(width3);
  print('Unsigned value of $num3 with width $width3: $unsignedValue3');
}

Output

Unsigned value of 10 with width 3: 2

Summary

In this Dart tutorial, we learned about toUnsigned() method of int: the syntax and few working examples with output and detailed explanation for each example.