Преобразование HEX в текст в JavaScript
Доброго времени суток! При работе с данными часто бывает так, что они приходят не в том формате/кодировке в которой мы их ожидаем. Поэтому, перед тем как начать работать с такими данными нам приходиться их преобразовать к нужному нам формату. Например, мне в одном из проектов клиента пришлось работать с текстовыми данными, которые должны были быть в формате ASCII, но в действительности оказались вшестнадцатеричном представлении (HEX). Для работы с этими данными их пришлось преобразовать из шестнадцатеричного формата в обычный понятный человеку текстовый формат с помощью следующей функции:
// конвертируем hex-строку в ascii-строку
function hex2text(hex_string)
const hex = hex_string.toString(); // конвертируем в строку
let out = »;
// i += 2 — так в шестнадцатеричном виде число представлено двумя символами
for (let i = 0; i < hex.length; i += 2)
// код символа в шестнадцетиричном представлении
const charCode = parseInt(hex.substr(i, 2), 16);
out += String.fromCharCode(charCode);
>
Функция ниже делает преобразование обратное предыдущей функции, т.е. из текста в HEX:
function text2hex(text)
let char;
let out = «»;
// проходимся циклом по всей строке и берем по одному символу
for(let i = 0; i < text.length; i++)
char = text.charCodeAt(i); // получаем код символа по индексу i
char = char.toString(16); // преобразуем число в шестнадцатеричное представление
out += char;
>
return out.toUpperCase(); // возвращаем строку в верхнем регистре
>
Таким образом, вот так просто можно преобразовать строку из одного представления (hex) в другое (text) в JavaScript.
Создано 23.03.2023 08:16:37
Копирование материалов разрешается только с указанием автора (Михаил Русаков) и индексируемой прямой ссылкой на сайт (http://myrusakov.ru)!
Добавляйтесь ко мне в друзья ВКонтакте: http://vk.com/myrusakov.
Если Вы хотите дать оценку мне и моей работе, то напишите её в моей группе: http://vk.com/rusakovmy.
Если Вы не хотите пропустить новые материалы на сайте,
то Вы можете подписаться на обновления: Подписаться на обновления
Если у Вас остались какие-либо вопросы, либо у Вас есть желание высказаться по поводу этой статьи, то Вы можете оставить свой комментарий внизу страницы.
Порекомендуйте эту статью друзьям:
Если Вам понравился сайт, то разместите ссылку на него (у себя на сайте, на форуме, в контакте):
- Кнопка:
Она выглядит вот так: - Текстовая ссылка:
Она выглядит вот так: Как создать свой сайт - BB-код ссылки для форумов (например, можете поставить её в подписи):
Комментарии ( 0 ):
Для добавления комментариев надо войти в систему.
Если Вы ещё не зарегистрированы на сайте, то сначала зарегистрируйтесь.
Copyright © 2010-2023 Русаков Михаил Юрьевич. Все права защищены.
Convert ASCII to Hexadecimal in JavaScript
- Convert an ASCII Character to Hexadecimal in JavaScript
- Converting a String of ASCII Into Hexadecimal Equivalent in JavaScript
- Convert Hexadecimal Back to ASCII
- Remarks
The main intention to develop the American Standard Code for Information Interchange (ASCII) was to exchange data between devices. ASCII is a code table that has human-readable characters and it consists of each character mapped to specific numbers (the so-called ASCII codes). Like the binary base number systems used by computers, we use hexadecimal number systems while transmitting data over a channel for error-free communication. ASCII is a human-readable format, which is internally used differently by computers. Let’s see how we can convert an ASCII value to a hex value with JavaScript.
Convert an ASCII Character to Hexadecimal in JavaScript
The conversion is easy and doesn’t require many steps in the code. Let us look at the code for converting an ASCII character to hexadecimal.
window.onload = function () convertASCIItoHex("A"); convertASCIItoHex("n"); convertASCIItoHex("!"); > function convertASCIItoHex(asciiVal) let asciiCode = asciiVal.charCodeAt(0); let hexValue = asciiCode.toString(16); console.log("0x" + hexValue); >
In this section, we are dealing with converting an ASCII character into the hexadecimal equivalent for it. We have the conversion process explained as follows.
In the window.onload() function of javascript, we call the convertASCIItoHex() function for translating the ASCII value to Hexadecimal in javascript. window.onload() function is called on page load so that the function gets executed as soon as the page loads.
In the convertASCIItoHex() function, we pass the ASCII value that needs to be converted. asciiVal.charCodeAt(0) returns the ASCII code of the input value passed in the convertASCIItoHex() function as parameter. The ASCII table contains a mapping to the human-readable letter format and a code associated with them. It looks like the following.
Once we get the ASCII code corresponding to the parameter value, our next step is to convert it into hexadecimal. In the snippet asciiCode.toString(16) , the .toString(16) function returns the hexadecimal value as a string. We store the hexadecimal string value in the hexValue variable.
In the final step, we console the hexadecimal equivalent of the passed attribute using the console.log() function of JavaScript.
Note
It may appear weird to append the 0x keyword to the converted Hexadecimal value. It is a common approach followed in javascript to identify the number as a hexadecimal value (Refer MSDN Docs for more details). For your business purpose, we can avoid it and follow the hexadecimal value output from the .toString(16) function.
The toString(16) function is a multipurpose function in javascript. We can use it to convert to different number base systems. We need to pass the decimal base or radix as a parameter to the function. If we look forward to a binary equivalent of the ASCII code, then the toString(2) function will return the binary equivalent of the decimal value. The function will typecast the object to a string before returning the binary value. And hence, return type of .toString() is string.
Converting a String of ASCII Into Hexadecimal Equivalent in JavaScript
The more common requirements we get in our lives are to convert a string as a whole into the hexadecimal equivalent value rather than a character. The following program takes a string as an input and returns a string of hexadecimal equivalent for each character as output. Each hex value will be separated by ‘ ‘ a space for better readability and understanding.
window.onload = function () convertASCIItoHex("Hello!"); convertASCIItoHex("Good Morning World!!"); > function convertASCIItoHex(asciiString) let hex = ''; let tempASCII, tempHex; asciiString.split('').map( i => tempASCII = i.charCodeAt(0) tempHex = tempASCII.toString(16); hex = hex + tempHex + ' '; >); hex = hex.trim(); console.log(hex); >
48 65 6c 6c 6f 21 47 6f 6f 64 20 4d 6f 72 6e 69 6e 67 20 57 6f 72 6c 64 21 21
Here the convertASCIItoHex() returns a hexadecimal string value corresponding to the string input provided. It will return a value of type String . The string of hex codes is separated by spaces for readability and clarity. Let us look at the steps we followed.
As discussed in the previous section, we call the window.onload() function of javascript and then call the convertASCIItoHex(«Hello!») function by passing a string «Hello!» as a parameter to it.
In the convertASCIItoHex() function, we split the input string into characters to make it easy to process them. Hence, at this phase, the «Hello!» string converts to [«H», «e», «l», «l», «o», «!»] , a string array.
Next, we apply the ASCII to hex conversion on each element of the array with the .map() operator of javascript. It iterates through each element and executes a function on each of them. We pass the function as an inline function or arrow function.
In the function, we use charCodeAt(0) to get the current array element’s ASCII code. Then, on the ASCII code object, we apply the toString(16) to convert the ASCII value to a hexadecimal base. Then we push the hexadecimal value to the hex array, the output array. Note that we use a space between the consecutive conversion for readability sake. You may also prefer using , or ; separator as demanded by the business needs.
With hex = hex + tempHex + ‘ ‘ we append a space after each element conversion. Hence, the final result will be having a trailing space. In order to remove that, we use the .trim() function of javascript.
Finally, the converted string array is logged into the console with the console.log(hex) .
Convert Hexadecimal Back to ASCII
Now, as we have the hexadecimal values ready, the question that arises is how do we confirm that the output is as expected. We achieve the core of the functionality with the fromCharCode(ASCIICode) function of javascript that returns the ASCII character corresponding to the ASCII code passed in the parameter. Here, we can use the following code.
window.onload = function () convertASCIItoHex("48 65 6c 6c 6f 21"); convertASCIItoHex("47 6f 6f 64 20 4d 6f 72 6e 69 6e 67 20 57 6f 72 6c 64 21 21"); > function convertHexToASCII(hexString) let stringOut = ''; hexString.split(' ').map( (i) => tempAsciiCode = parseInt(i, 16); stringOut = stringOut + String.fromCharCode(tempAsciiCode); >); console.log(stringOut); >
A couple of methods do the magic here. parseInt(i, 16) converts an input of base 16 to decimal base. Hence, with this method, we get the ASCII code for the hex value. And the String.fromCharCode(tempAsciiCode) takes the ASCII code passed as a parameter to this function and returns the ASCII character corresponding to the code.
Remarks
- The most commonly used human-readable form of ASCII includes Alphabets, numbers, and special characters. With the javascript codes, we intend to cover these character sets. We cannot test certain ASCII codes in JavaScript, like the ACK: Acknowledge character, ETX: End of Text character, etc.
- JavaScript string variable can hold a length of maximum 2 53 -1 characters as per ES8 standards. And that amounts to roughly 512MB of data in chrome and around a Gigabyte of data in Firefox. Hence, we can convert longer string values using our code.
Copyright © 2023. All right reserved