Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(104)

Unified Diff: sdk/lib/core/int.dart

Issue 23645003: Esoteric bit operations. (Closed) Base URL: https://dart.googlecode.com/svn/branches/bleeding_edge/dart
Patch Set: Created 7 years, 3 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View side-by-side diff with in-line comments
Download patch
Index: sdk/lib/core/int.dart
diff --git a/sdk/lib/core/int.dart b/sdk/lib/core/int.dart
index 96a6d40e6dc5654b8e2e3d5d130d52dfbf25365b..1651f226bde847e8cfa8836f2f46dfd92ca734f5 100644
--- a/sdk/lib/core/int.dart
+++ b/sdk/lib/core/int.dart
@@ -99,6 +99,56 @@ abstract class int extends num {
bool get isOdd;
/**
+ * Returns the minimum number of bits required to store this integer.
+ *
+ * The number of bits excludes the sign bit, which gives the natural length
+ * for non-negative (unsigned) values. Negative values are complemented to
+ * return the bit position of the first bit that differs from the sign bit.
+ *
+ * To find the the number of bits needed to store the value as a signed value,
+ * add one, i.e. use `x.bitLength + 1`.
+ *
+ * x.bitLength == (-x-1).bitLength
+ *
+ * 3.bitLength == 2; // 00000011
+ * 2.bitLength == 2; // 00000010
+ * 1.bitLength == 1; // 00000001
+ * 0.bitLength == 0; // 00000000
+ * (-1).bitLength == 0; // 11111111
+ * (-2).bitLength == 1; // 11111110
+ * (-3).bitLength == 2; // 11111101
+ * (-4).bitLength == 2; // 11111100
+ */
+ int get bitLength;
+
+ /**
+ * 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].
+ *
+ * (-1).toUnsigned(5) == 32 // 11111111 -> 00011111
+ *
+ * This operation can be used to simulate arithmetic from low level languages.
+ * For example, to increment an 8 bit quantity:
+ *
+ * q = (q + 1).toUnsigned(8);
+ */
+ int toUnsigned(int width);
+
+ /**
+ * 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].
+ *
+ * V--sign bit-V
+ * 16.toSigned(5) == -16 // 00010000 -> 11110000
+ * 239.toSigned(5) == 15 // 11101111 -> 00001111
+ * ^ ^
Lasse Reichstein Nielsen 2013/09/06 12:40:11 If I'm correct then x == x.toSigned(x.bitLength
sra1 2013/09/06 22:11:57 I added this relation to the documentation.
+ */
+ int toSigned(int width);
+
+ /**
* Return the negative value of this integer.
*
* The result of negating an integer always has the opposite sign, except

Powered by Google App Engine
This is Rietveld 408576698