Recursive AI

Convert JavaScript bytes to Base64 and hex in C#

OneEcma is a free, open-source JavaScript interpreter for .NET from Recursive AI. MIT or Apache-2.0, no native dependencies.

Terminal
dotnet add package RecursiveAI.OneEcma

Requires .NET 10 (net10.0); .NET 9 and earlier aren’t supported.

C#
using RecursiveAI.OneEcma;
 
var engine = new ScriptEngine();
Console.WriteLine(engine.Evaluate("""
  const bytes = new Uint8Array([0, 42, 255]);
  const b64 = bytes.toBase64();
  const hex = bytes.toHex();
  [b64, hex, Uint8Array.fromBase64(b64),
   Uint8Array.fromHex(hex)].join("\n");
  """).AsString);

Unzip the example, then dotnet run.

Prints the two encodings, then the decoded bytes from each.

Text
ACr/
002aff
0,42,255
0,42,255

Full program

The full program decodes the same three bytes and then tries two invalid inputs: the odd-length hex string abc and Base64 Zh== with strict padding checks.

C#
using RecursiveAI.OneEcma;
 
var engine = new ScriptEngine();
Console.WriteLine(engine.Evaluate("""
    const bytes = new Uint8Array([0, 42, 255]);
    const base64 = bytes.toBase64();
    const hex = bytes.toHex();
    const strict = { lastChunkHandling: "strict" };
    const output = [
      `Base64: ${base64}; bytes: ${Uint8Array.fromBase64(base64, strict)}`,
      `Hex: ${hex}; bytes: ${Uint8Array.fromHex(hex)}`,
    ];
    const invalid = [
      ["odd hex", () => Uint8Array.fromHex("abc")],
      ["non-zero padding bits", () => Uint8Array.fromBase64("Zh==", strict)],
    ];
    for (const [label, decode] of invalid) {
      try { decode(); }
      catch (error) { output.push(`${label}: ${error.name}: ${error.message}`); }
    }
    output.join("\n");
    """).AsString);

dotnet run prints:

Text
Base64: ACr/; bytes: 0,42,255
Hex: 002aff; bytes: 0,42,255
odd hex: SyntaxError: The hex input has an odd length
non-zero padding bits: SyntaxError: The base64 input has non-zero padding bits

Catch SyntaxError in JavaScript to reject a malformed text payload; if it escapes the script, C# receives a JsException.

Variations

Use Base64url without trailing =. Pass the same alphabet option when you decode; the default decoder mode accepts the unpadded final chunk.

C#
using RecursiveAI.OneEcma;
 
var engine = new ScriptEngine();
Console.WriteLine(engine.Evaluate("""
  const bytes = new Uint8Array([255]);
  const url = { alphabet: "base64url", omitPadding: true };
  const encoded = bytes.toBase64(url);
  const decoded = Uint8Array.fromBase64(encoded, url);
  `${encoded} -> ${decoded[0]}`;
  """).AsString);
Text
_w -> 255

The short answer

Call bytes.toBase64() or bytes.toHex() on a JavaScript Uint8Array. To get bytes back, call Uint8Array.fromBase64(text) or Uint8Array.fromHex(text). In a C# host, the JavaScript encodings are strings and can be read as JsValue.AsString. The decoded results in the example remain typed arrays inside JavaScript; the program prints their byte values so you can see what survived the round trip. To get the decoded bytes as a C# byte[], see Exchange JavaScript typed arrays with C#.

How do you convert a Uint8Array to a Base64 string and back?

Use toBase64 directly on the byte view. The method encodes the bytes it can see, not every byte in the buffer if the view covers only part of it. fromBase64 creates a new Uint8Array. Neither operation interprets the bytes as UTF-8. If the payload represents text, its character encoding is a separate decision.

The standard alphabet in the full program produces ACr/, including a slash. If the format calls for Base64url, use alphabet: "base64url" so the encoder uses - and _ in place of + and /, and select the same alphabet on decode. Whether to omit = is a separate option. Use the variation’s unpadded output only if your receiver accepts that form.

For inputs that must have a complete final chunk and zero padding bits, select lastChunkHandling: "strict". In the full program Zh== looks padded, but it puts nonzero bits in the unused part of the final chunk. Strict mode rejects it; the canonical Base64 for that one byte is Zg==. OneEcma documents its own decoder error messages. In applications, branch on the error type rather than matching the English wording.

How do you convert a Uint8Array to a hex string?

toHex gives two lowercase digits per byte, including leading zeros. The sample 002aff is three bytes: 00, 2a, and ff. Hex makes it straightforward to inspect individual bytes. Base64 uses four characters per three input bytes for a full chunk, so it produces shorter strings than hex for longer payloads.

fromHex expects pairs of hex digits, not a number literal or a formatted dump. An odd digit count, 0x prefix, or separator makes the string invalid. Keep hex as text until you decode it, so a numeric conversion cannot discard leading zero bytes.

All oneecma recipes