3

I am trying to send a byte array pulled from my database via C# to my front end client, which is written in JavaScript/TypeScript, but it seems that the byte array is being encoded somewhere between being sent from the back end and getting to the front end.

The data in the database is a varbinary with the value: 0x00000001. I've set a breakpoint where my C# code is returning the retrieved value and I am getting a byte array with the value of: [0, 0, 0, 1]. However, when it gets to the client, the value is: "AAAAAQ==".

I've tried decoding it using the following code:

let encodedString = encodeURI(encodeURIComponent(flag));

let arr = [];
for (let i = 0; i < encodedString.length; i++) {
    arr.push(encodedString.charCodeAt(i));
}

But that code returns this array of values: [65, 65, 65, 65, 65, 81, 37, 50, 53, 51, 68, 37, 50, 53, 51, 68]

What is causing the data to be encoded, and how can I either decode it in TypeScript or prevent it from encoded when it is being sent to the client?

CodyCS
  • 59
  • 1
  • 2
  • 11

1 Answers1

5

"AAAAAQ==" is the Base64 encoded version of 0x00000001. As such you'll need to convert it back using atob then push each char code in to an array.

let text = 'AAAAAQ==';

let bin = atob(text);

let bytes = [];
for (let i = 0; i< bin.length; i++){
    bytes.push(bin.charCodeAt(i));
}

console.log(bytes);
phuzi
  • 12,078
  • 3
  • 26
  • 50
  • Worked perfectly! Thank you very much! – CodyCS Apr 17 '18 at 13:13
  • 1
    This is a great answer (have upvoted). If you have non-latin characters (e.g. Chinese), `atob` might not handle it well. See https://stackoverflow.com/questions/30106476/using-javascripts-atob-to-decode-base64-doesnt-properly-decode-utf-8-strings – JsAndDotNet Nov 05 '20 at 12:46