Erro convert Hex to Ascii Javascript - javascript

I receive a binary file (biometric template) and I must convert the hexadecimal caracter to a ASCII caracter. But some hexadecimal caracter the programm do not convert, like hex = 95.
What is wrong? What must I to do for the program convert every ?
bellow the code:
var campo = document.getElementById('fileInput');
var hex = campo.toString();
var str = '';
for (var i = 0; i < prm.length; i += 2)
str += String.fromCharCode(parseInt(prm.substr(i, 2), 16));

You don't specify what you mean by "do not convert". If you meant decimal 95, there is an ASCII character but it is not printable (NAK). There is no ASCII character for hex 0x95 because ASCII is a 7-bit encoding (0-0x7f). And JavaScript strings are not ASCII, they're UCS-2.
https://mathiasbynens.be/notes/javascript-encoding

Related

Elegant way to split hex string at byte 00?

I need to split a hex string at every 00 byte. I tried this:
string.split('00');
But that causes splits at 5009, for instance, which is incorrect because it is splitting a byte in half.
In other words, it turns 5009 to [5, 9], which I don't want. But I do want it to turn af0059 to [af, 59].
Is it even possible to split bytes using regex, without cutting any bytes in half?
I could use a loop to seek through the string and only divide the string at even-number indices, but I would much prefer a regex expression.
Because of the byte sizes, you need to first split the string into byte-sizes, then map and finally join.
const string = "af00b9e00f70";
const res = string.split(/([\d\w]{4})/).filter(e => e).map(e => e.replace(/00([\d\w]{2})/, "$1").replace(/([\d\w]{2})00/, "$1")).join("");
console.log(res);
Here's a somewhat "old school' approach, but it demonstrates the principal. I say "old school' because we had to do this all the time back in the days of assembler coding. 'string' contains your long string of hex pairs (bytes). Here I convert it to byte values. Change the 'string' to whatever you want, but be sure it has an even number of hex digits. Call 'translate' to demonstrate it, and format the output into an alert() (or just output to the console)
var values = []; // output array
var string = "000102030405060708090a0b0c0d0e0f1FFFFEFDFCFBFAF9F8F7F6F5F4F3F2F0";
function getHexByteValues( string) {
var hex= "0123456789ABCDEF";
var outIx=0;
for (var i =0; i <= (string.length-2); i +=2) { // skip every other
//get higher and lower nibble
var hexdig1 = string.substring(i, i+1);
var hexdig0 = string.substring(i+1, i+2);
// for simplicity, convert alpha to upper case
hexdig1 = hexdig1.toUpperCase();
hexdig0 = hexdig0.toUpperCase();
// convert hex to decimal value.
// position in lookup string == value
var dec1 = hex.indexOf(hexdig1);
var dec0 = hex.indexOf(hexdig0);
// calc "byte" value, and add to values.
values[outIx++] = dec1 * 16 + dec0;
}
}
function translate(string) {
getHexByteValues(string);
var output="";
for (var i =0; i < values.length; i++) {
output += i + " = " + values[i] + "\r\n";
}
alert (output);
}
Maybe not the most elegant, but it works
const inp = "af00b9e00f70"
const out = inp.match(/.{1,2}/g).map(a=>a=="00"?"_":a).join("").split("_");
console.log(out);

Converting from utf8 to hex and back with Javascript

I'm trying to encrypt text using WebCrypto. I convert the result to a utf8 string, then convert that to hex. The encryption/decryption works. However, I want to convert the data to hex. When I try to convert to hex and back, the result is different.
Here's the fiddle (use Chrome): https://jsfiddle.net/yxp01v5g/
The test code is here:
var text = "hello world";
var key = App.crypto.generateKey(16);
App.crypto.encrypt(text, key, function(encryptedText, iv){
console.log("encrypted text:", encryptedText, "iv", iv);
var encryptedTextHex = convertUtf8StringToHex(encryptedText);
console.log("encrypted text hex", encryptedTextHex);
var backToUtf8 = convertHexToUtf8(encryptedTextHex);
console.log("Back to utf8", backToUtf8);
console.assert(encryptedText == backToUtf8);
})
As you can see, I'm taking the result, converting it to hex, then converting it back to utf8, hoping for it to be equal to the original result. However, it's not.
Can anyone tell me what on earth I'm doing wrong?
I didn't dig too deep into the call-chain used in the fiddle to do the conversion, but it appears to try converting UTF-16/UCS-2 to byte size instead of an actually hex representation of the buffer content itself.
Here is one approach to convert the byte buffer content to hex string representation, and from hex string back to binary data.
It takes each byte in the buffer and produced a two-digit hex representation of its value, and concatenates it to a string.
The reverse takes two chars from the string representation and converts it back to a byte value representation.
// some bytes as Uint8Array
var random = crypto.getRandomValues(new Uint8Array(16)), i, str = "", allOK = true;
// convert to HEX string representation
for(i = 0; i < random.length; i++) str += pad2(random[i].toString(16));
console.log(str);
// convert back to byte buffer
var buffer = new Uint8Array(random.length);
for(i = 0; i < buffer.length; i++) buffer[i] = parseInt(str.substr(i<<1, 2), 16);
// check if same content
for(i = 0; i < buffer.length; i++) if (buffer[i] !== random[i]) allOK = false;
console.log("All OK?", allOK)
function pad2(s) {return s.length < 2 ? "0" + s : s}; // helper: pad to 2 digits

Hex Number to Char using Javascript

How do I convert, for example, the string "C3" to its character using JavaScript? I've tried charCodeAt, toString(16) and everything, doesn't work.
var justtesting= "C3"; //there's an input here
var tohexformat= '\x' + justtesting; //gives wrong hex number
var finalstring= tohexformat.toString(16);
All you need is parseInt and possibly String.fromCharCode.
parseInt accepts a string and a radix, a.k.a the base you wish to convert from.
console.log(parseInt('F', 16));
String.fromCharCode will take a character code and convert it to the matching string.
console.log(String.fromCharCode(65));
So here's how you can convert C3 into a number and, optionally, into a character.
var input = 'C3';
var decimalValue = parseInt(input, 16); // Base 16 or hexadecimal
var character = String.fromCharCode(decimalValue);
console.log('Input:', input);
console.log('Decimal value:', decimalValue);
console.log('Character representation:', character);
Another simple way is to print "&#"+ CharCode like this
for(var i=9984;i<=10175;i++){
document.write(i+ " " + i.toString(16) + " &#" + i +"<br>");
}
OR
for(var i=0x2700;i<=0x27BF;i++){
document.write(i+ " " + i.toString(16) + " &#" + i +"<br>");
}
JSFIDDLE

Encode string into decimal digits - javascript

Is there a way to encode regular javascript utf-8 string into decimal 0-9 ( or octal 0-7 if that's more convenient) (octal or base10) ?
I saw this thread for php, I want similar for javascript.
Encoding byte data into digits
Not sure why you want to do this exactly, but depending on your needs, it's easy enough. JavaScript's String.prototype.charCodeAt() returns the numeric Unicode value of the characters in a string, which can go up to 65,536 (assuming your are not using unicode codepoints > 0x10000; if you are, consult the String.prototype.charCodeAt documentation).
Chances are, you're using ASCII, meaning your numeric character codes will be, at most, 255, meaning you could get by with three digits. So first we'll need a function to pad zeros:
function zeroPad(n, w){
while(n.toString().length<w) n = '0' + n;
return n;
}
Then we can create a function to convert your string to a string of numbers:
function toNumbers(s){
var nums = '';
for(var i=0; i<s.length; i++) {
nums += zeroPad(s.charCodeAt(i), 3);
}
return nums;
}
Then a function to decode:
function fromNumbers(nums){
var s = '';
for(var i=0; i<nums.length; i+=3){
console.log(i + ': ' + nums.substring(i, i+3))
s += String.fromCharCode(nums.substring(i, i+3));
}
return s;
}

Get the Value of a byte with Javascript

I'm not sure if the title makes any sense, but here is what I need.
This is my byte: ���������ˇ�����0F*E��ù� �
I have already managed to get the values of this byte with this php snippet:
<?php
$var = "���������ˇ�����0F*E��ù�";
for($i = 0; $i < strlen($var); $i++)
{
echo ord($var[$i])."<br/>";
}
?>
The result was:
0
0
0
0
0
0
0
0
2
2
0
255
0
0
0
0
0
2
48
70
1
42
69
0
0
1
157
0
But now I need to do the exact same thing without php, but in Java Script.
Any help would be appreciated
If you're wanting to get the numeric value of each character in a string in JavaScript, that can be done like so:
var someString = "blarg";
for(var i=0;i<someString.length;i++) {
var char = someString.charCodeAt(i);
}
String.charCodeAt(index) returns the Unicode code-point value of the specified character in the string. It does not behave like PHP or C where it returns the numeric value of a fixed 8-bit encoding (i.e. ASCII). Assuming your string is a human-readable string (as opposed to raw binary data) then using charCodeAt is perfectly fine. If you're working with raw binary data then don't use a JavaScript string.
If your strings contain characters that have Unicode code-points below 128 then charCodeAt behaves the same as ord in PHP or C's char type, however the example you've provided contains non-ASCII characters, so Unicode's (sometimes complicated) rules will come into play.
See the documentation on charCodeAt here: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/charCodeAt
The PHP String is computed as 8-bit (bytes 0..255) while JavaScript uses 16-bit unicode characters (0..65535). Depending on your string you may either split it into (16bit) char codes or into the bytes. If you know your String contains only 8-bit chars you may ignore the "hiByte" (see below) to get the same results as in PHP.
function toByteVersionA(s) {
var len = s.length;
// char codes
var charCodes = new Array();
for(var i=0; i<len; i++) {
charCodes.push(s.charCodeAt(i).toString());
}
var charCodesString = charCodes.join(" ");
return charCodesString;
}
function toByteVersionB(s) {
var len = s.length;
var bytes = new Array();
for(var i=0; i<len; i++) {
var charCode = s.charCodeAt(i);
var loByte = charCode & 255;
var hiByte = charCode >> 8;
bytes.push(loByte.toString());
bytes.push(hiByte.toString());
}
var bytesString = bytes.join(" ");
return bytesString;
}
function toByteVersionC(s) {
var len = s.length;
var bytes = new Array();
for(var i=0; i<len; i++) {
var charCode = s.charCodeAt(i);
var loByte = charCode & 255;
bytes.push(loByte.toString());
}
var bytesString = bytes.join(" ");
return bytesString;
}
var myString = "abc"; // whatever your String is
var myBytes = toByteVersionA(myString); // whatever version you want

Categories

Resources