What is the best way to change a number into a byte string using TypeScript?

If I have a number represented by 3 bytes in hexadecimal form as 0x303132, how can I transform this number into a string of three characters with the same value - '012' - where each character represents the ASCII value of the corresponding byte? I am aware that one way to achieve this is by using '\x', but I am looking for a solution that does not involve hard-coding the value.

Answer №1

Given that the input consists of a series of hexadecimal values (each represented by two characters), my approach involves utilizing a regular expression to disregard the initial header "0x." Subsequently, I extract pairs of valid characters and apply them to the transformation function within the String.replace method. This function converts the extracted hex value into decimal, followed by converting that decimal value into its corresponding ASCII character.

input = "0xABCD"
output = input.replace(/(?:0x)?([0-9a-f]{2})/ig, function (match, $1) {
return String.fromCharCode(parseInt($1, 16));
})

console.log(output)

Answer №2

Here is my concise functional solution (without regex, JQuery, or lodash), the variable v holds the String

const s = Array.from(Array((v.length-2)/2).keys()).reduce(
    (acc, i) => acc + String.fromCharCode(parseInt(v.slice(2+i*2, 2+(i+1)*2),16)),
     ""
)

Explore it in this TypeScript playground

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

Utilizing Typescript with Angular 2 to efficiently convert JSON data into objects within HTTP requests

I am dealing with a file called location.json, which contains JSON data structured like this: { "locations": [ { "id": 1, "places": [ { "id": 1, "city": "A ...

Tips for transferring data to an entry component in Angular 2 using ng-bootstrap modal

I've been grappling with sending data to a custom modal content component in Angular 2. My objective is to have the flexibility of calling this modal from any other component without duplicating code. Despite my efforts, including referencing the "Com ...

What is the best way to customize the tooltip in VS Code for TypeScript type aliases?

Here is an issue with the code snippet below: type char = 'a' | 'b' | 'c' | 'd' | 'e' | 'f'; const s: string = 'foo'; const [c]: char = s; // [ERROR]: Type 'string' is not assi ...

closing custom components in Ag-Grid React columns

I am currently utilizing version "27.1.0" of "ag-grid-react". In order to display a custom column component that presents a set of options and closes when the user makes a selection, I need it to trigger an API call. Since this component does not re-render ...

What is the process for importing a file with an .mts extension in a CJS-first project?

Here's a snippet from a fetchin.mts file: import type { RequestInfo, RequestInit, Response } from "node-fetch"; const importDynamic = new Function("modulePath", "return import(modulePath);") export async function fetch(u ...

Mastering Vue3: Typed Component Instance Template Refs with Exposed Methods

In my project, I am working with a component called A that has a method called send. Here is an example of how Component A is structured in A.vue: <script setup lang="ts"> function send(data: string) { console.log(data) } defineExpose({ ...

Having troubles with *ngFor in Angular 8? Learn how to use ng-template effectively

I need assistance creating a table with dynamically generated columns and using the PrimeNg library for the grid. Despite asking several questions, I have not received any responses. Can someone please help me achieve this? To generate table column heade ...

Is it possible to create a distinctive property value within an ngFor loop that operates autonomously across two child components?

I am working on a functionality where, upon clicking on a specific car brand, the name of the person and their favorite car will be displayed at the bottom. However, I'm facing an issue where the car brand is being repeated among all items in the ngFo ...

Adding elements from one array to another array of a different type while also including an additional element (JavaScript/TypeScript)

I'm having trouble manipulating arrays of different types, specifically when working with interfaces. It's a simple issue, but I could use some help. Here are the two interfaces I'm using: export interface Group { gId: number; gName: st ...

Obtain precise measurements of a modified image using the Sharp library

My Cloud Function successfully resizes images uploaded to Cloud Storage using Sharp. However, I am facing an issue with extracting metadata such as the exact height and width of the new image. I am contemplating creating a new function that utilizes diff ...

Testing the MatDialog Component

Currently, I am in the process of creating a unit test for my confirmation modal that relies on MatDialog. The initial test I have set up is a simple one to ensure that the component is successfully created. Below is the code snippet from my spec file: im ...

Is it necessary for me to set up @types/node? It appears that VSCode comes with it pre-installed

Many individuals have been adding @types/node to their development dependencies. Yet, if you were to open a blank folder in VSCode and create an empty JavaScript file, then input: const fs = require('fs'); // <= hover it and the type display ...

Is it possible to apply search filters within a child component in Angular?

I have a situation where I am passing data from a parent component to a child component using *ngFor / @input. The child component is created multiple times based on the number of objects in the pciData array. pciData consists of around 700 data objects, ...

How come the path alias I defined is not being recognized?

Summary: I am encountering error TS2307 while trying to import a file using an alias path configured in tsconfig.json, despite believing the path is correct. The structure of directories in my Angular/nx/TypeScript project appears as follows: project |- ...

Do [(ngModel)] bindings strictly adhere to being strings?

Imagine a scenario where you have a radiobutton HTML element within an angular application, <div class="radio"> <label> <input type="radio" name="approvedeny" value="true" [(ngModel)]=_approvedOrDenied> Approve < ...

Disabling eslint does not prevent errors from occurring for the unicorn/filename-case rule

I have a file called payment-shipping.tsx and eslint is throwing an error Filename is not in camel case. Rename it to 'paymentShipping.tsx' unicorn/filename-case However, the file needs to be in kebab case since it's a next.js page that s ...

Sending the HTML input value to a Knockout view

Can someone assist me with a dilemma I'm facing? Within CRM on Demand, I have a view that needs to extract values from CRM input fields to conduct a search against CRM via web service. If duplicate records are found, the view should display them. Be ...

Tips for addressing the browser global object in TypeScript when it is located within a separate namespace with the identical name

Currently diving into TypeScript and trying to figure out how to reference the global Math namespace within another namespace named Math. Here's a snippet of what I'm working with: namespace THREE { namespace Math { export function p ...

Switch up the styling of a component by updating its properties with a switch statement

Although there is a similar question, my query has a unique requirement. I have defined the common styles for my button and implemented a function using a switch statement with different properties for various buttons across different pages. However, for ...

ERROR TS1086: A declaration of an accessor within an ambient context is not allowed. Accessor for firebaseUiConfig(): NativeFirebaseUIAuthConfig

Trying to create a Single Page Application with Angular/CLI 8. Everything was running smoothly locally until I tried to add Firebase authentication to the app. Upon compiling through Visual Studio Code, I encountered the following error message: ERROR in ...