Вопрос:

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

java string

1844 просмотра

2 ответа

16 Репутация автора

public static void main(String[] args) {
    try {
        String name = "i love my country";
        byte[] sigToVerify = name.getBytes();
        System.out.println("file data:" + sigToVerify);
        String name1 = "data";
        byte[] sigToVerify1 = name1.getBytes();
        System.out.println("file data1:" + sigToVerify1);

    }
}

I am trying to execute the above program but getBytes() gives me different values for the same String. Is there any way to get the same byte while executing multiple times for a given string?

Автор: user123 Источник Размещён: 26.09.2014 06:45

Ответы (2)


8 плюса

11300 Репутация автора

Решение
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));
Автор: Steve Benett Размещён: 26.09.2014 09:19

1 плюс

762 Репутация автора

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.

Автор: Dave Размещён: 26.09.2014 09:33
Вопросы из категории :
32x32