Java Integer.toUnsignedString()
方法
原文:https://www.studytonight.com/java-wrapper-class/java-integer-tounsignedstring-int-int-method
Java toUnsignedString()
方法是java.lang
包的Integer
类的一部分。此方法用于返回在传递的基(基数)中作为参数传递的整数值的无符号字符串等价物。
例如,toUnsignedString(65,2)
将返回 1000001,因为在基数 2 中作为无符号值的 65 的值是 1000001,而toUnsignedString(-65,2)
将返回 111111111111111111110111111,因为在基数 2 中作为无符号值的-65 的值是 11111111111111111111111101111111。
必须注意,如果基数值小于Character.MIN_RADIX
或大于 Character.MAX_RADIX
,则使用基数 10。
语法:
public static String toUnsignedString(int i, int radix)
参数:
传递的参数是int i
和int radix
,前者的无符号字符串等价物将被返回,后者定义了字符串转换的基础。
返回:
返回与根据作为参数传递的基数值传递的整数值等效的无符号字符串。
例 1:
这里,根据基数值,整数值被转换成其等价的无符号字符串表示形式。
import java.lang.Integer;
public class StudyTonight
{
public static void main(String[] args)
{
int a = -78;
int b = 78;
int d = 10;
int h = 16;
int o = 8;
String s1 = Integer.toUnsignedString(a,d); //Returns the unsigned string representation of the integer value with radix 10
System.out.println("Equivalent String Value = " + s1);
String s2 = Integer.toUnsignedString(a,h); //Returns the unsigned string representation of the integer value with radix 16
System.out.println("Equivalent String Value = " + s2);
String s3 = Integer.toUnsignedString(a, o); //Returns the unsigned string representation of the integer value with radix 8
System.out.println("Equivalent String Value = " + s3);
String s4 = Integer.toUnsignedString(b, d); //Returns the unsigned string representation of the integer value with radix 10
System.out.println("Equivalent String Value = " + s4);
String s5 = Integer.toUnsignedString(b, h); //Returns the unsigned string representation of the integer value with radix 16
System.out.println("Equivalent String Value = " + s5);
String s6 = Integer.toUnsignedString(b, o); //Returns the unsigned string representation of the integer value with radix 8
System.out.println("Equivalent String Value = " + s6);
}
}
等效字符串值= -78 等效字符串值= -4e 等效字符串值= -116 等效字符串值= 78 等效字符串值= 4e 等效字符串值= 116
例 2:
这里有一个用户定义的例子,任何使用这段代码的人都可以输入自己选择的值,并获得等效的输出。
import java.util.Scanner;
public class StudyTonight
{
public static void main(String[] args)
{
try
{
System.out.println("Enter the value and base ");
Scanner sc = new Scanner(System.in);
int val = sc.nextInt();
int b = sc.nextInt();
System.out.println("Output: "+Integer.toUnsignedString(val, b)); //returns string with equivalent base
}
catch(Exception e)
{
System.out.println("Invalid Input!!");
}
}
}
输入数值和基数 68 8 输出:104 *输入数值和基数 -82 16 输出:ffffffae *输入数值和基数 0x389 8 无效输入!!
实时示例:
在这里,您可以测试实时代码示例。您可以为不同的值执行示例,甚至可以编辑和编写您的示例来测试 Java 代码。