@@ -41,7 +41,7 @@ func init() {
41
41
py .MustNewMethod ("globals" , py .InternalMethodGlobals , 0 , globals_doc ),
42
42
py .MustNewMethod ("hasattr" , builtin_hasattr , 0 , hasattr_doc ),
43
43
// py.MustNewMethod("hash", builtin_hash, 0, hash_doc),
44
- // py.MustNewMethod("hex", builtin_hex, 0, hex_doc),
44
+ py .MustNewMethod ("hex" , builtin_hex , 0 , hex_doc ),
45
45
// py.MustNewMethod("id", builtin_id, 0, id_doc),
46
46
// py.MustNewMethod("input", builtin_input, 0, input_doc),
47
47
py .MustNewMethod ("isinstance" , builtin_isinstance , 0 , isinstance_doc ),
@@ -826,6 +826,52 @@ object.
826
826
The globals and locals are dictionaries, defaulting to the current
827
827
globals and locals. If only globals is given, locals defaults to it.`
828
828
829
+ const hex_doc = `hex(number) -> string
830
+
831
+ Return the hexadecimal representation of an integer.
832
+
833
+ >>> hex(12648430)
834
+ '0xc0ffee'
835
+ `
836
+
837
+ func builtin_hex (self , v py.Object ) (py.Object , error ) {
838
+ var (
839
+ i int64
840
+ err error
841
+ )
842
+ switch v := v .(type ) {
843
+ case * py.BigInt :
844
+ // test bigint first to make sure we correctly handle the case
845
+ // where int64 isn't large enough.
846
+ vv := (* big .Int )(v )
847
+ format := "%#x"
848
+ if vv .Cmp (big .NewInt (0 )) == - 1 {
849
+ format = "%+#x"
850
+ }
851
+ str := fmt .Sprintf (format , vv )
852
+ return py .String (str ), nil
853
+ case py.IGoInt64 :
854
+ i , err = v .GoInt64 ()
855
+ case py.IGoInt :
856
+ var vv int
857
+ vv , err = v .GoInt ()
858
+ i = int64 (vv )
859
+ default :
860
+ return nil , py .ExceptionNewf (py .TypeError , "'%s' object cannot be interpreted as an integer" , v .Type ().Name )
861
+ }
862
+
863
+ if err != nil {
864
+ return nil , err
865
+ }
866
+
867
+ format := "%#x"
868
+ if i < 0 {
869
+ format = "%+#x"
870
+ }
871
+ str := fmt .Sprintf (format , i )
872
+ return py .String (str ), nil
873
+ }
874
+
829
875
const isinstance_doc = `isinstance(obj, class_or_tuple) -> bool
830
876
831
877
Return whether an object is an instance of a class or of a subclass thereof.
0 commit comments