String.getBytes() returns different values for multiple execution?

后端 未结 2 1550
public static void main(String[] args) {
    try {
        String name = \"i love my country\";
        byte[] sigToVerify = name.getBytes();
        System.out.println(         


        
相关标签:
2条回答
  • 2021-01-22 18:35
    System.out.println("file data:" + sigToVerify);
    

    Here you are not printing the value of a String. As owlstead pointed out correctly in the comments, the Object.toString() method will be invoked on the byte array sigToVerify. Leading to an output of this format:

    getClass().getName() + '@' + Integer.toHexString(hashCode())
    

    If you want to print each element in the array you have to loop through it.

    byte[] bytes = "i love my country".getBytes();
    for(byte b : bytes) {
        System.out.println("byte = " + b);
    }
    

    Or even simpler, use the Arrays.toString() method:

    System.out.println(Arrays.toString(bytes));
    
    0 讨论(0)
  • 2021-01-22 18:52

    try printing out the contents of the byte array instead of the toString() result of the variable

    for(byte b : sigToVerify)
        System.out.print(b +"\t");
    

    if the bytes getting printed are the same, then you're good to go.

    0 讨论(0)
提交回复
热议问题