Converting hexadecimal to binary using Javascript or Typescript before writing a file on an Android or iOS device

Hey everyone! I'm facing a puzzling issue and I can't seem to figure out why it's happening.

I need to download a file that is stored in hex format, so I have to first read it as hex, convert it to binary, and then write it onto an Android/iOS device.

In order to achieve this, in my React project, I read the file from the machine, convert it to binary, and then send it to the native code for writing the file.

This is the code snippet from my React (NOT React Native) project:

Firstly, I read the file:

async readFileContent(path: string, isNotBin = true): Promise<string> {
     // Code block for reading the file
}

Next, here's the conversion function:

private hex2bin(hex: string): string | string[] | Uint8Array {
    // Conversion logic from hex to bin
}

Finally, sending the content to native code:

viewFile(content: string, fileName: string): Promise<ViewFileResult> {
    // Sending content to native code
}

Everything seems fine up until this point. However, when I check the content in the native viewFile function, I notice some weird characters being added unnecessarily (in hex they're equivalent to C2) and the final part of the content is cut off.

Any insights or ideas on what might be causing this issue would be greatly appreciated!

Answer №1

When I run a console.log(content) within the viewFile function, the content appears to be accurate.

However, it's important to note that a string in JavaScript is essentially a sequence of UTF-16 characters, meaning it consists of 2/4/8-byte sequences, each containing a character.

If your goal is to write a binary file, then you must ensure that you are working with binary content.
The hex2bin function should take a hexadecimal string as input and convert it into a byte array, effectively returning the 'view'. Therefore, the return type of hex2bin needs to be changed to Uint8Array.

In order to handle binary data correctly, you will need to update sendNativeContent (not shown in this context) to use a binary signature that accepts content in the form of a Uint8Array.

Converting a binary sequence into a JavaScript string will inevitably distort the data permanently.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

React: Using useState and useEffect to dynamically gather a real-time collection of 10 items

When I type a keystroke, I want to retrieve 10 usernames. Currently, I only get a username back if it exactly matches a username in the jsonplaceholder list. For example, if I type "Karia", nothing shows up until I type "Karianne". What I'm looking f ...

Add custom scripts to individual components within a Vue.js application

After extensive searching, I still can't seem to find a solution to my current issue. My focus is on a Vue project with vue-cli, where I need to inject various scripts into different pages (leveraging vue-router). Here are more specific details: Thi ...

Replace or update the current array of objects that align with the incoming array

I've been struggling to figure out how to find and replace an array that matches the existing one. The issue lies with using the some method. Here is the current array: let existingData = [{ id: 1, product: 'Soap', price: ' ...

JavaScript that is subtle and lacks function parameters

Suppose you have: <div id="data" onclick="handleData(1)">Datum 1</div> and you prefer late binding instead: <div id="data">Datum 1</div> <script> $("#data").click(function() { handleData(1); }) </script&g ...

Error alert: Unable to find the specified word

Having trouble writing a word to the database due to an error: ReferenceError: Patikrinta is not defined. Below is my ajax script for sending data to a PHP file, and then the PHP script itself if needed. Haven't found a solution on Stack Overflow. $s ...

Guide to triggering a change event on a react-number-format component

I am attempting to trigger a change event in order to modify the value of a react-number-format component within my component. During testing, I encounter a TypeError: value.replace is not a function error on the simulate('change', event) method ...

Guide on creating a detailed list of categories mapped to specific classes that all adhere to a common generic standard

Most TypeScript factory patterns I've encountered rely on a named mapping between a name and the Class type. A basic implementation example: const myMap = { classOne: ExampleClass, classTwo: AnotherClass } (k: string) => { return new myMap[k] } ...

Converting JSON data into TypeScript interface objects within an Angular 2 environment

I have a JSON dataset with the following structure: { "timestamp": 1467471622, "base": "USD", "rates": { "AED": 3.673027, "AFN": 68.475, "ALL": 123.095199, "AMD": 476.8075, "ANG": 1.78385, "AOA": 165.846832, "ARS": 15.05 ...

Handling empty values in JSON data when sending it to the controller through AJAX

Attempting to transmit the following JSON data from View to Controller: { "allselected": false, "selectedIds": ["", "all"], "targetControl": "Studieniva", "targetSource": "studienivalist", "dependency": [{ "name": "ShopNo", ...

Changing the color of a Highcharts series bar according to its value

Playing around with Highcharts in this plunker has led me to wonder if it's possible to dynamically set the color of a bar based on its value. In my current setup, I have 5 bars that change values between 0 and 100 at intervals. I'd like the colo ...

What purpose does the next() function serve in Express.js?

Using this script to kickstart my next js app. I can't share the entire script, but I do need some assistance with the following: What is the purpose of compression? What is the importance of using helmet? What does next({dev}) do? const express = re ...

Problem with Anular5 - "this" not functioning correctly inside of ready()

I am encountering an issue in graph.component.ts this.cContainer = cytoscape ( { ready: function(e) { this._dataService.setResultData(); } }); However, I am getting the following error message: ERROR TypeError: Cannot read property &ap ...

Each attempt to install a new package results in a syntax error pointing to "gyp err"

While in the process of installing Firebase, I encountered a similar issue when attempting to install yarn add react-router-dom. To resolve this, I had to create a new project and manually copy over all the files again. What stood out to me was that this ...

Make the most of your Bootstrap 3 layout by utilizing a full page container that fills both the width and height between a fixed header and

I am currently working on a basic bootstrap page with the Example template from Bootstrap's website. I want the content in the middle to take up the space between the header and footer, while ensuring that both the header and footer remain visible at ...

What is the reason behind lightbox not disabling scrolling?

While using the default lightbox2 CSS and JavaScript, everything is functioning correctly except for an issue on Safari mobile. When I click an image and the lightbox opens, swiping to the left reveals blank white space despite having overflow-x set to hid ...

Iterating through a JSON object and an array

I've been attempting to iterate through a JSON object but I'm struggling with it. Below is the JSON object I need to work with. This JSON data will be fetched from another website, and my goal is to loop through it to extract certain details. ...

What could be causing an error in a scroll handler when using React's setState function?

Upon reaching the bottom of the page and scrolling back up, an error is thrown by React stating "TypeError: _this.setState is not a function" The scroll handler in question monitors the position of the client on the page. If the client is within the home ...

Exploring LZMA compression in conjunction with next.js

Is anyone familiar with using the lzma algorithm to compress video, photo, text, etc. in the Next.js framework? I have searched everywhere but couldn't find a solution. I haven't found a proper demonstration or answer anywhere. I would greatly a ...

Guide on adding an additional key:value pair to a sub document in a MongoDB collection

I'm facing difficulties trying to add a new key:value pair to an existing object in a MongoDB document. I've experimented with $each, $push, and $addToSet, but it seems like those are intended for arrays. I then attempted $set, but that only upd ...

Error message indicating that the function is not defined within a custom class method

I successfully transformed an array of type A into an object with instances of the Person class. However, I'm facing an issue where I can't invoke methods of the Person class using the transformed array. Despite all console.log checks showing tha ...