@@ -215,15 +215,17 @@ public long toLong() {
215215 }
216216 long res = 0 ;
217217 for (int i = bits .used -1 , j = 0 ; i >= 0 ; i --, j ++) {
218- res = res + table [i ].value () * pow (2 , j );
218+ res = res + table [i ].value () * ( int ) pow (2 , j );
219219 }
220220 return res ;
221221 }
222222
223- private static int pow (int m , int n ){
224- int res = 1 ;
225- for (int i = 0 ; i < n ; i ++) {
226- res *= m ;
223+ private static double pow (int m , int n ){
224+ if (m == 0 ) return 0 ;
225+ double md = (n >= 0 ) ? m : 1.0 / m ;
226+ double res = 1 ;
227+ for (int i = 0 ; i < Math .abs (n ); i ++) {
228+ res *= md ;
227229 }
228230 return res ;
229231 }
@@ -715,4 +717,42 @@ public static Bits encodeStringValue(String value) {
715717 return Bits .ofByte (value .getBytes (StandardCharsets .UTF_8 ));
716718 }
717719 }
720+
721+ public static class Decoder {
722+ public static int decodeIntValue (Bits value ) {
723+ int res = 0 ;
724+ for (int i = value .length () - 1 , j = 0 ; i >= 0 ; i --, j ++) {
725+ res = res + value .get (i ).value () * (int )pow (2 , j );
726+ }
727+ return res ;
728+ }
729+
730+ public static double decodeDecimalValue (Bits value ) {
731+ double res = 0 ;
732+ for (int i = 0 , j = 0 ; i < value .length (); i ++, j ++) {
733+ res = res + value .get (i ).value () * pow (2 , -(j +1 ));
734+ }
735+ return res ;
736+ }
737+
738+ public static float decodeFloatValue (Bits value ) {
739+ if (value .length () != 32 ) throw new IllegalArgumentException ("float value must be 32 bits" );
740+ Bits bits = value .clone ();
741+ int S = bits .get (0 ).value ();
742+ int E = bits .subBits (1 , 9 ).toInt () - 127 ;
743+ Bits M = Bits .ofOne ().append (bits .subBits (9 , 32 ));
744+ float floatValue = (float ) (decodeIntValue (M .subBits (0 , 1 + E )) + decodeDecimalValue (M .subBits (1 + E , M .length ())));
745+ return (S == 0 ? 1 : -1 ) * floatValue ;
746+ }
747+
748+ public static double decodeDoubleValue (Bits value ) {
749+ if (value .length () != 64 ) throw new IllegalArgumentException ("double value must be 64 bits" );
750+ Bits bits = value .clone ();
751+ int S = bits .get (0 ).value ();
752+ int E = bits .subBits (1 , 12 ).toInt () - 1023 ;
753+ Bits M = Bits .ofOne ().append (bits .subBits (12 , 64 ));
754+ double doubleValue = decodeIntValue (M .subBits (0 , 1 + E )) + decodeDecimalValue (M .subBits (1 + E , M .length ()));
755+ return (S == 0 ? 1 : -1 ) * doubleValue ;
756+ }
757+ }
718758}
0 commit comments