Browse Source

Make hex_to_int and bin_to_int handle the prefix automatically

Also add BinToInt to C#
Aaron Franke 4 years ago
parent
commit
a3e3bf8227

+ 9 - 13
core/string/ustring.cpp

@@ -2097,8 +2097,9 @@ String::String(const StrRange &p_range) {
 	copy_from(p_range.c_str, p_range.len);
 }
 
-int64_t String::hex_to_int(bool p_with_prefix) const {
-	if (p_with_prefix && length() < 3) {
+int64_t String::hex_to_int() const {
+	int len = length();
+	if (len == 0) {
 		return 0;
 	}
 
@@ -2110,10 +2111,7 @@ int64_t String::hex_to_int(bool p_with_prefix) const {
 		s++;
 	}
 
-	if (p_with_prefix) {
-		if (s[0] != '0' || s[1] != 'x') {
-			return 0;
-		}
+	if (len > 2 && s[0] == '0' && s[1] == 'x') {
 		s += 2;
 	}
 
@@ -2140,8 +2138,9 @@ int64_t String::hex_to_int(bool p_with_prefix) const {
 	return hex * sign;
 }
 
-int64_t String::bin_to_int(bool p_with_prefix) const {
-	if (p_with_prefix && length() < 3) {
+int64_t String::bin_to_int() const {
+	int len = length();
+	if (len == 0) {
 		return 0;
 	}
 
@@ -2153,10 +2152,7 @@ int64_t String::bin_to_int(bool p_with_prefix) const {
 		s++;
 	}
 
-	if (p_with_prefix) {
-		if (s[0] != '0' || s[1] != 'b') {
-			return 0;
-		}
+	if (len > 2 && s[0] == '0' && s[1] == 'b') {
 		s += 2;
 	}
 
@@ -4251,7 +4247,7 @@ bool String::is_valid_ip_address() const {
 				continue;
 			}
 			if (n.is_valid_hex_number(false)) {
-				int64_t nint = n.hex_to_int(false);
+				int64_t nint = n.hex_to_int();
 				if (nint < 0 || nint > 0xffff) {
 					return false;
 				}

+ 2 - 2
core/string/ustring.h

@@ -318,8 +318,8 @@ public:
 	bool is_numeric() const;
 
 	double to_float() const;
-	int64_t hex_to_int(bool p_with_prefix = true) const;
-	int64_t bin_to_int(bool p_with_prefix = true) const;
+	int64_t hex_to_int() const;
+	int64_t bin_to_int() const;
 	int64_t to_int() const;
 
 	static int64_t to_int(const char *p_str, int p_len = -1);

+ 2 - 2
core/variant/variant_call.cpp

@@ -968,8 +968,8 @@ static void _register_variant_builtin_methods() {
 
 	bind_method(String, to_int, sarray(), varray());
 	bind_method(String, to_float, sarray(), varray());
-	bind_method(String, hex_to_int, sarray("with_prefix"), varray(true));
-	bind_method(String, bin_to_int, sarray("with_prefix"), varray(true));
+	bind_method(String, hex_to_int, sarray(), varray());
+	bind_method(String, bin_to_int, sarray(), varray());
 
 	bind_method(String, lpad, sarray("min_length", "character"), varray(" "));
 	bind_method(String, rpad, sarray("min_length", "character"), varray(" "));

+ 22 - 9
doc/classes/String.xml

@@ -63,9 +63,18 @@
 		<method name="bin_to_int">
 			<return type="int">
 			</return>
-			<argument index="0" name="with_prefix" type="bool" default="true">
-			</argument>
 			<description>
+				Converts a string containing a binary number into an integer. Binary strings can either be prefixed with [code]0b[/code] or not, and they can also start with a [code]-[/code] before the optional prefix.
+				[codeblocks]
+				[gdscript]
+				print("0x101".bin_to_int()) # Prints "5".
+				print("101".bin_to_int()) # Prints "5".
+				[/gdscript]
+				[csharp]
+				GD.Print("0x101".BinToInt()); // Prints "5".
+				GD.Print("101".BinToInt()); // Prints "5".
+				[/csharp]
+				[/codeblocks]
 			</description>
 		</method>
 		<method name="c_escape">
@@ -221,14 +230,18 @@
 		<method name="hex_to_int">
 			<return type="int">
 			</return>
-			<argument index="0" name="with_prefix" type="bool" default="true">
-			</argument>
 			<description>
-				Converts a string containing a hexadecimal number into a decimal integer. If [code]with_prefix[/code] is [code]true[/code], the hexadecimal string should start with the [code]0x[/code] prefix, otherwise [code]0[/code] is returned.
-				[codeblock]
-				print("0xff".hex_to_int()) # Print "255"
-				print("ab".hex_to_int(false)) # Print "171"
-				[/codeblock]
+				Converts a string containing a hexadecimal number into an integer. Hexadecimal strings can either be prefixed with [code]0x[/code] or not, and they can also start with a [code]-[/code] before the optional prefix.
+				[codeblocks]
+				[gdscript]
+				print("0xff".hex_to_int()) # Prints "255".
+				print("ab".hex_to_int()) # Prints "171".
+				[/gdscript]
+				[csharp]
+				GD.Print("0xff".HexToInt()); // Prints "255".
+				GD.Print("ab".HexToInt()); // Prints "171".
+				[/csharp]
+				[/codeblocks]
 			</description>
 		</method>
 		<method name="http_escape">

+ 47 - 6
modules/mono/glue/GodotSharp/GodotSharp/Core/StringExtensions.cs

@@ -97,6 +97,36 @@ namespace Godot
             return b;
         }
 
+        /// <summary>
+        /// Converts a string containing a binary number into an integer.
+        /// Binary strings can either be prefixed with `0b` or not,
+        /// and they can also start with a `-` before the optional prefix.
+        /// </summary>
+        /// <param name="instance">The string to convert.</param>
+        /// <returns>The converted string.</returns>
+        public static int BinToInt(this string instance)
+        {
+            if (instance.Length == 0)
+            {
+                return 0;
+            }
+
+            int sign = 1;
+
+            if (instance[0] == '-')
+            {
+                sign = -1;
+                instance = instance.Substring(1);
+            }
+
+            if (instance.StartsWith("0b"))
+            {
+                instance = instance.Substring(2);
+            }
+
+            return sign * Convert.ToInt32(instance, 2);;
+        }
+
         // <summary>
         // Return the amount of substrings in string.
         // </summary>
@@ -493,11 +523,20 @@ namespace Godot
             return ret;
         }
 
-        // <summary>
-        // Convert a string containing an hexadecimal number into an int.
-        // </summary>
+        /// <summary>
+        /// Converts a string containing a hexadecimal number into an integer.
+        /// Hexadecimal strings can either be prefixed with `0x` or not,
+        /// and they can also start with a `-` before the optional prefix.
+        /// </summary>
+        /// <param name="instance">The string to convert.</param>
+        /// <returns>The converted string.</returns>
         public static int HexToInt(this string instance)
         {
+            if (instance.Length == 0)
+            {
+                return 0;
+            }
+
             int sign = 1;
 
             if (instance[0] == '-')
@@ -506,10 +545,12 @@ namespace Godot
                 instance = instance.Substring(1);
             }
 
-            if (!instance.StartsWith("0x"))
-                return 0;
+            if (instance.StartsWith("0x"))
+            {
+                instance = instance.Substring(2);
+            }
 
-            return sign * int.Parse(instance.Substring(2), NumberStyles.HexNumber);
+            return sign * int.Parse(instance, NumberStyles.HexNumber);
         }
 
         // <summary>

+ 1 - 1
servers/rendering/shader_language.cpp

@@ -643,7 +643,7 @@ ShaderLanguage::Token ShaderLanguage::_get_token() {
 					}
 
 					if (hexa_found) {
-						tk.constant = (double)str.hex_to_int(true);
+						tk.constant = (double)str.hex_to_int();
 					} else {
 						tk.constant = str.to_float();
 					}

+ 1 - 4
tests/test_string.h

@@ -370,12 +370,9 @@ TEST_CASE("[String] String to integer") {
 TEST_CASE("[String] Hex to integer") {
 	static const char *nums[4] = { "0xFFAE", "22", "0", "AADDAD" };
 	static const int64_t num[4] = { 0xFFAE, 0x22, 0, 0xAADDAD };
-	static const bool wo_prefix[4] = { false, true, true, true };
-	static const bool w_prefix[4] = { true, false, true, false };
 
 	for (int i = 0; i < 4; i++) {
-		CHECK((String(nums[i]).hex_to_int(true) == num[i]) == w_prefix[i]);
-		CHECK((String(nums[i]).hex_to_int(false) == num[i]) == wo_prefix[i]);
+		CHECK(String(nums[i]).hex_to_int() == num[i]);
 	}
 }