Dart int toSigned()
Syntax & Examples

int.toSigned() method

The `toSigned` method in Dart returns the least significant width bits of this integer, extending the highest retained bit to the sign.


Syntax of int.toSigned()

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.

Parameters

ParameterOptional/RequiredDescription
widthrequiredThe number of bits to keep.

Return Type

int.toSigned() returns value of type int.



✐ Examples

1 Convert an integer to signed 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 a signed value with width1 using the toSigned() method.
  3. We print the result to standard output.

Dart Program

void main() {
  int num1 = 5;
  int width1 = 4;
  int signedValue1 = num1.toSigned(width1);
  print('Signed value of $num1 with width $width1: $signedValue1');
}

Output

Signed value of 5 with width 4: 5

2 Convert a negative integer to signed 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 a signed value with width2 using the toSigned() method.
  3. We print the result to standard output.

Dart Program

void main() {
  int num2 = -3;
  int width2 = 6;
  int signedValue2 = num2.toSigned(width2);
  print('Signed value of $num2 with width $width2: $signedValue2');
}

Output

Signed value of -3 with width 6: -3

3 Convert a positive integer to signed 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 a signed value with width3 using the toSigned() method.
  3. We print the result to standard output.

Dart Program

void main() {
  int num3 = 10;
  int width3 = 3;
  int signedValue3 = num3.toSigned(width3);
  print('Signed value of $num3 with width $width3: $signedValue3');
}

Output

Signed value of 10 with width 3: 2

Summary

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.