负整数到字节Java

负整数到字节Java,java,Java,我的问题是,当int为负值时,我不能正确计算int的长度 第二个问题是,当整数小于10位时,如果函数不能忽略最后一位,那么如何解决这个问题呢 int number = -123456789; int length = (int) (Math.log10(number) + 1); System.out.println("Variable length is: " + length + " digits \nThis is: " + number); if (number <= -1) {

我的问题是,当int为负值时,我不能正确计算int的长度

第二个问题是,当整数小于10位时,如果函数不能忽略最后一位,那么如何解决这个问题呢

int number = -123456789;
int length = (int) (Math.log10(number) + 1);
System.out.println("Variable length is: " + length + " digits \nThis is: " + number);

if (number <= -1) {
    System.out.println("We have negative variable");
    String negative = Integer.toString(number);
    System.out.println(negative);

    if (negative.substring(10, 11).isEmpty()||
        negative.substring(10, 11).equals("") ||
        negative.substring(10, 11) == "" ||
        negative.substring(10, 11).equals(null) ||
        negative.substring(10, 11) == null)
    {
        System.out.println("Nothing");
    } else {
        String separate_10 = negative.substring(10, 11);
        System.out.println("Last digit (10): " + separate_10);
        int int_10 = Integer.parseInt(separate_10);
        byte result = (byte) int_10;
    }
    String group = "Existing result is: " + result;
    System.out.println(group);
}
int number=-123456789;
整数长度=(整数)(数学log10(数字)+1);
System.out.println(“可变长度为:“+length+”位\n这是:“+number”);

如果(数字字符串的索引从
0
开始,那么当您这样做时

negative.substring(10, 11) 
第11个索引超出了范围,因为最后一个字符位于索引10,即
'9'
,您可以使用

negative.charAt(negative.length() - 1)
在不硬编码任何索引值的情况下获取最后一个字符


要获得负整数的长度,只需执行
negative.length()-1
,即可从图片中获取
'-'
字符

或者只是

int getIntLength(int integer) {
    String intStr = Integer.toString(integer);
    return intStr.length() + (integer < 0 ? -1 : 0);
}
int getIntLength(int整数){
字符串intStr=Integer.toString(整数);
返回intStr.length()+(整数<0?-1:0);
}

要获取长度,无论是负值还是正值

请注意,
Math.log10
为负值输入返回
NaN
(不是一个数字)。这不清楚您在问什么。您是否正在尝试计算数字中的位数?如果要将int转换为字节,为什么不只是
Number&0xff