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
Parameter | Optional/Required | Description |
---|---|---|
width | required | The 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,
- We assign the value
5
to the integer variablenum1
and specifywidth1
as 4. - We convert
num1
to an unsigned value withwidth1
using thetoUnsigned()
method. - 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,
- We assign the value
-3
to the integer variablenum2
and specifywidth2
as 6. - We convert
num2
to an unsigned value withwidth2
using thetoUnsigned()
method. - 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,
- We assign the value
10
to the integer variablenum3
and specifywidth3
as 3. - We convert
num3
to an unsigned value withwidth3
using thetoUnsigned()
method. - 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.