Dart BigInt toSigned()
Syntax & Examples


BigInt.toSigned() method

The `toSigned()` method of BigInt class returns the least significant `width` bits of this BigInt, extending the highest retained bit to the sign.


Syntax of BigInt.toSigned()

The syntax of BigInt.toSigned() method is:

 BigInt toSigned(int width) 

This toSigned() method of BigInt 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 retain

Return Type

BigInt.toSigned() returns value of type BigInt.



✐ Examples

1 Convert BigInt to signed value with 64 bits

In this example,

  1. We create a BigInt bigInt with a large value.
  2. We use the toSigned() method to convert it to a signed value with 64 bits.
  3. We print the signed value to standard output.

Dart Program

void main() {
  BigInt bigInt = BigInt.parse('12345678901234567890');
  BigInt signedValue = bigInt.toSigned(64);
  print('Signed value with 64 bits: $signedValue');
}

Output

Signed value with 64 bits: -6101065172474983726

2 Convert BigInt to signed value with 32 bits

In this example,

  1. We create a BigInt bigInt with a large negative value.
  2. We use the toSigned() method to convert it to a signed value with 32 bits.
  3. We print the signed value to standard output.

Dart Program

void main() {
  BigInt bigInt = BigInt.parse('-98765432109876543210');
  BigInt signedValue = bigInt.toSigned(32);
  print('Signed value with 32 bits: $signedValue');
}

Output

Signed value with 32 bits: 450461974

Summary

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