@@ -3578,6 +3578,65 @@ class Strings {
35783578 }
35793579
35803580
3581+ /**
3582+ * Static extension for <code>Int</code>.
3583+ *
3584+ * <pre><code>
3585+ * >>> Strings.toBinary(1) == "1"
3586+ * >>> Strings.toBinary(2) == "10"
3587+ * >>> Strings.toBinary(10) == "1010"
3588+ * >>> Strings.toBinary(10, 8) == "00001010"
3589+ * >>> Strings.toBinary(255) == "11111111"
3590+ * >>> Strings.toBinary(-1) == "11111111111111111111111111111111"
3591+ * >>> Strings.toBinary(-10, 8) == "11110110"
3592+ * </code></pre>
3593+ *
3594+ * @param minDigits the resulting string is left padded with <code>0</code> until it length equals <code>minDigits</code>
3595+ * @return the binary representation of <b>num</b>
3596+ */
3597+ public static function toBinary (num : Int , ? minDigits : Int ): String {
3598+ var result : String ;
3599+
3600+ #if cs
3601+ result = cs.system. Convert . ToString (num , 2 );
3602+ #elseif java
3603+ result = java.lang. Integer .toBinaryString (num );
3604+ #elseif js
3605+ result = untyped (num >>> 0 ).toString (2 );
3606+ #elseif php
3607+ // Force 32-bit two's complement for negatives, then decbin
3608+ result = (php. Syntax .code (" decbin({0} & 0xFFFFFFFF)" , num ) : String );
3609+ #elseif python
3610+ // Keep 32-bit two's complement for negatives (match other targets)
3611+ result = python. Syntax .code (" format({0} & 0xFFFFFFFF, 'b')" , num );
3612+ #else
3613+ if (num == 0 ) {
3614+ result = " 0" ;
3615+ } else {
3616+ var bits = new Array <String >();
3617+ var v = num ;
3618+ // Logical shift to shrink even negative ints to 0 in 32 steps
3619+ while (v != 0 ) {
3620+ bits .push (((v & 1 ) != 0 ) ? " 1" : " 0" );
3621+ v >>> = 1 ;
3622+ }
3623+ bits .reverse ();
3624+ result = bits .join (" " );
3625+ }
3626+ #end
3627+
3628+ if (minDigits != null ) {
3629+ // For negatives we want the rightmost minDigits bits (trim leading ones from 32-bit form)
3630+ if (num < 0 && result .length > minDigits ) {
3631+ result = result .substr (result .length - minDigits );
3632+ }
3633+ // Then pad with zeros on the left if still shorter
3634+ result = StringTools .lpad (result , " 0" , minDigits );
3635+ }
3636+ return result ;
3637+ }
3638+
3639+
35813640 /**
35823641 * Static extension for <code>Int</code>.
35833642 *
0 commit comments