0

java code --

String plainText = "thisismyplaintext";
byte[] bytes = plainText.getBytes("UTF-8");

System.out.println(bytes);
// Output - [B@3cd1a2f1

I am trying to do the same thing in javascript but I am always getting absolutely different output like example - [11, 12, 14, 16].

I have tried everything from different stackoverfow answers but nothing is working similar to this java code.

Please help me to achieve the same thing in javascript and to get similar output.

10
  • 1
    Please keep in mind that Java and JavaScript are not the same programming language and correct the tags. Commented Jul 20, 2019 at 6:48
  • @JayJamesJay I think OP is aware of this. OP wants to translate the Java code to Javascript code Commented Jul 20, 2019 at 6:49
  • 1
    @Nick Parsons You're right, my mistake. Commented Jul 20, 2019 at 6:50
  • The output of java Byte arrays is the object reference. Read about object.toString(). You will not be able to get this in JavaScript. Commented Jul 20, 2019 at 6:58
  • Is there a way to achieve same thing in Node.js. Sorry I have not mentioned that I am actually using Node.js I know Node.js is also javascript but there's lot's of library available. Commented Jul 20, 2019 at 7:30

1 Answer 1

1

[B@3cd1a2f1 is not the result you are after. [B@3cd1a2f1 represents the class type ([B) of your array of bytes and the hex representation of your array's hash. You need to instead print the array contents, which can be done using Arrays.toString():

String plainText = "thisismyplaintext";
byte[] bytes = plainText.getBytes(StandardCharsets.UTF_8);
System.out.println(Arrays.toString(bytes));

This will give the array:

[116, 104, 105, 115, 105, 115, 109, 121, 112, 108, 97, 105, 110, 116, 101, 120, 116]

This you can get the same result in Javascript using the following:

const str = "thisismyplaintext";
const utf8 = unescape(encodeURIComponent(str));
const arr = [...utf8].map(c => c.charCodeAt(0));
console.log(arr);

- Credit to this answer for byte array algorithm

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your answer. I was unaware of that what is happening in that java code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.