The `toUnsigned` method in Dart returns the least significant width bits of this integer as a non-negative number (i.e., unsigned representation).
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.
Parameter | Optional/Required | Description |
---|---|---|
width | required | The number of bits to keep. |
int.toUnsigned() returns value of type int
.
In this example,
5
to the integer variable num1
and specify width1
as 4.num1
to an unsigned value with width1
using the toUnsigned()
method.void main() {
int num1 = 5;
int width1 = 4;
int unsignedValue1 = num1.toUnsigned(width1);
print('Unsigned value of $num1 with width $width1: $unsignedValue1');
}
Unsigned value of 5 with width 4: 5
In this example,
-3
to the integer variable num2
and specify width2
as 6.num2
to an unsigned value with width2
using the toUnsigned()
method.void main() {
int num2 = -3;
int width2 = 6;
int unsignedValue2 = num2.toUnsigned(width2);
print('Unsigned value of $num2 with width $width2: $unsignedValue2');
}
Unsigned value of -3 with width 6: 61
In this example,
10
to the integer variable num3
and specify width3
as 3.num3
to an unsigned value with width3
using the toUnsigned()
method.void main() {
int num3 = 10;
int width3 = 3;
int unsignedValue3 = num3.toUnsigned(width3);
print('Unsigned value of $num3 with width $width3: $unsignedValue3');
}
Unsigned value of 10 with width 3: 2
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.