The `toSigned` method in Dart returns the least significant width bits of this integer, extending the highest retained bit to the sign.
The syntax of int.toSigned() method is:
int toSigned(int width)
This toSigned() method of int returns the least significant width bits of this integer, extending the highest retained bit to the sign. This is the same as truncating the value to fit in width bits using an signed 2-s complement representation. The returned value has the same bit value in all positions higher than width.
Parameter | Optional/Required | Description |
---|---|---|
width | required | The number of bits to keep. |
int.toSigned() returns value of type int
.
In this example,
5
to the integer variable num1
and specify width1
as 4.num1
to a signed value with width1
using the toSigned()
method.void main() {
int num1 = 5;
int width1 = 4;
int signedValue1 = num1.toSigned(width1);
print('Signed value of $num1 with width $width1: $signedValue1');
}
Signed value of 5 with width 4: 5
In this example,
-3
to the integer variable num2
and specify width2
as 6.num2
to a signed value with width2
using the toSigned()
method.void main() {
int num2 = -3;
int width2 = 6;
int signedValue2 = num2.toSigned(width2);
print('Signed value of $num2 with width $width2: $signedValue2');
}
Signed value of -3 with width 6: -3
In this example,
10
to the integer variable num3
and specify width3
as 3.num3
to a signed value with width3
using the toSigned()
method.void main() {
int num3 = 10;
int width3 = 3;
int signedValue3 = num3.toSigned(width3);
print('Signed value of $num3 with width $width3: $signedValue3');
}
Signed value of 10 with width 3: 2
In this Dart tutorial, we learned about toSigned() method of int: the syntax and few working examples with output and detailed explanation for each example.