How can I convert a char/string in JS to uint8? - node.js
Say I have a str char:
const s = '\n';
how can I convert to uint8? I believe the right value is 10.
You'll need to create a Buffer using Buffer.from(). That will give you a Buffer instance, from that you can use Buffer.readUInt8() to get the UInt8 representation of the Buffer.
function stringToUInt8 (s, offset) {
return Buffer.from(s).readUInt8(offset)
}
console.log(stringToUInt8('\n'))
Related
Decode value of base64 string in different language gives different output
I have a base64 string like this String value = "fefWUeQvPgBe/9QaG/RdPnn9PrzQK2VhVwBzAIr7eei9PQrZA2/sXTA/2SCodnTSJn4Lk+ve5kuPGjco4ljYrjNTsrKBAjN6APSHn0BqBce2lOZbm/z29U6j7j79niPbYl/UIc0VTjc0IgRhmNLn1eVvMTuoaGhlwlxUf/+xenC4NmEM2A6y5/DNRheNw6OrmHik/kowpWGQsRNFyXJ2VtzE54nqs9naePBkRlWna/oqBxzA/txtHXn8h/9xTT2caozcU5/R9JayFZq7ZeclzGs2DAACr1TyQwEb9JJpBXr04Zu4rlWLtnSbyflyK3lnSAocma0L6ENnCZoMiN8gUg==" I used this method to decode string in java Base64Utils.decode(value.getBytes()) output:125,-25,-42,81,-28,47,62,0,94,-1,-44,26,27,-12,93,62,121,-3,62,-68,-48,43,101,97,87,0,115,0,-118,-5,121,-24,-67,61,10,-39,3,111,-20,93,48,63,-39,32,-88,118,116,-46,38,126,11,-109,-21,-34,-26,75,-113,26,55,40,-30,88,-40,-82,51,83,-78,-78,-127,2,51,122,0,-12,-121,-97,64,106,5,-57,-74,-108,-26,91,-101,-4,-10,-11,78,-93,-18,62,-3,-98,35,-37,98,95,-44,33,-51,21,78,55,52,34,4,97,-104,-46,-25,-43,-27,111,49,59,-88,104,104,101,-62,92,84,127,-1,-79,122,112,-72,54,97,12,-40,14,-78,-25,-16,-51,70,23,-115,-61,-93,-85,-104,120,-92,-2,74,48,-91,97,-112,-79,19,69,-55,114,118,86,-36,-60,-25,-119,-22,-77,-39,-38,120,-16,100,70,85,-89,107,-6,42,7,28,-64,-2,-36,109,29,121,-4,-121,-1,113,77,61,-100,106,-116,-36,83,-97,-47,-12,-106,-78,21,-102,-69,101,-25,37,-52,107,54,12,0,2,-81,84,-14,67,1,27,-12,-110,105,5,122,-12,-31,-101,-72,-82,85,-117,-74,116,-101,-55,-7,114,43,121,103,72,10,28,-103,-83,11,-24,67,103,9,-102,12,-120,-33,32,82, then I used this method to decode string in nodejs Buffer.from(value, 'base64') output:125,231,214,81,228,47,62,0,94,255,212,26,27,244,93,62,121,253,62,188,208,43,101,97,87,0,115,0,138,251,121,232,189,61,10,217,3,111,236,93,48,63,217,32,168,118,116,210,38,126,11,147,235,222,230,75,143,26,55,40,226,88,216,174,51,83,178,178,129,2,51,122,0,244,135,159,64,106,5,199,182,148,230,91,155,252,246,245,78,163,238,62,253,158,35,219,98,95,212,33,205,21,78,55,52,34,4,97,152,210,231,213,229,111,49,59,168,104,104,101,194,92,84,127,255,177,122,112,184,54,97,12,216,14,178,231,240,205,70,23,141,195,163,171,152,120,164,254,74,48,165,97,144,177,19,69,201,114,118,86,220,196,231,137,234,179,217,218,120,240,100,70,85,167,107,250,42,7,28,192,254,220,109,29,121,252,135,255,113,77,61,156,106,140,220,83,159,209,244,150,178,21,154,187,101,231,37,204,107,54,12,0,2,175,84,242,67,1,27,244,146,105,5,122,244,225,155,184,174,85,139,182,116,155,201,249,114,43,121,103,72,10,28,153,173,11,232,67,103,9,154,12,136,223,32,82 The java output is what I really want to get, why its different? How can I correctly get decoded value in nodejs
Base64Utils.decode returns a signed 8 bit value in Java. Buffer.from returns an unsigned 8 bit value in Nodejs. While both return 8 bit (byte) values, the Java method interprets the high order bit as a negative number. Nodejs is unsigned. var value = 'fefWUeQvPgBe/9QaG/RdPnn9PrzQK2VhVwBzAIr\ 7eei9PQrZA2/sXTA/2SCodnTSJn4Lk+ve5kuPGj\ co4ljYrjNTsrKBAjN6APSHn0BqBce2lOZbm/z29\ U6j7j79niPbYl/UIc0VTjc0IgRhmNLn1eVvMTuo\ aGhlwlxUf/+xenC4NmEM2A6y5/DNRheNw6OrmHi\ k/kowpWGQsRNFyXJ2VtzE54nqs9naePBkRlWna/\ oqBxzA/txtHXn8h/9xTT2caozcU5/R9JayFZq7Z\ eclzGs2DAACr1TyQwEb9JJpBXr04Zu4rlWLtnSb\ yflyK3lnSAocma0L6ENnCZoMiN8gUg==' buffervalue = Buffer.from(value, 'base64'); for (i=0; i < buffervalue.length; i++) { y = buffervalue[i]; if (y > 127) { y = -(256 - y); } console.log(y); }
Grabbing first number in string after some keyword occurrence in C++ (Arduino)
I have a string coming from PC through serial to a microcontroller (Arduino), e.g.: "HDD: 55 - CPU: 12.6 - Weather: Cloudy [...] $"; by this function I found: String inputStringPC = ""; boolean stringCompletePC = false; void serialEvent() { while (Serial.available()) { char inChar = (char)Serial.read(); inputStringPC += inChar; if (inChar == '$') // end marker of the string { stringCompletePC = true; } } } I would like to extract the first number of it after the word HDD, CPU and also get the string after Weather (ie "cloudy"); my thinking is something like that: int HDD = <function that does that>(Keyword HDD); double CPU = <function that does that>(Keyword CPU); char Weather[] = <function that does that>(Keyword Weather); What is the right function to do that? I looked into inputStringSerial.indexOf("HDD") but I am still a learner to properly understand what it does and don't know if theres a better function. My approach yielded some syntax errors and confused me with the difference in usage between "String inputStringSerial" (class?) and "char inputStringSerial[]" (variable?). When I do 'string inputStringSerial = "";' PlatformIO complains that "string" is undefined. Any help to understand its usage here is greatly appreciated. Thanks a bunch.
The String class provides member functions to search and copy the contents of the String. That class and all its member functions are documented in the Arduino Reference: https://www.arduino.cc/reference/tr/language/variables/data-types/stringobject/ The other way a list of characters can be represented is a char array, confusingly also called a string or cstring. The functions to search and copy the contents of a char array are documented at http://www.cplusplus.com/reference/cstring/ Here is a simple Sketch that copies and prints the value of the Weather field using a String object. Use this same pattern - with different head and terminator values - to copy the string values of the other fields. Once you have the string values of HDD and CPU, you'll need to call functions to convert those string values into int and float values. See the String member functions toInt() and toFloat() at https://www.arduino.cc/reference/en/language/variables/data-types/string/functions/toint/ or the char array functions atoi() and atof() at http://www.cplusplus.com/reference/cstdlib/atoi/?kw=atoi String inputStringPC = "HDD: 55 - CPU: 12.6 - Weather: Cloudy [...] $"; const char headWeather[] = "Weather: "; // the prefix of the weather value const char dashTerminator[] = " -"; // one possible suffix of a value const char dollarTerminator[] = " $"; // the other possible suffix of a value void setup() { int firstIndex; // index into inputStringPC of the first char of the value int lastIndex; // index just past the last character of the value Serial.begin(9600); // find the Weather field and copy its string value. // Use similar code to copy the values of the other fields. // NOTE: This code contains no error checking for unexpected input values. firstIndex = inputStringPC.indexOf(headWeather); firstIndex += strlen(headWeather); // firstIndex is now the index of the char just past the head. lastIndex = inputStringPC.indexOf(dollarTerminator, firstIndex); String value = inputStringPC.substring(firstIndex, lastIndex); Serial.print("Weather value = '"); Serial.print(value); Serial.println("'"); } void loop() { // put your main code here, to run repeatedly: } When run on an Arduio Uno, this Sketch produces: Weather value = 'Cloudy [...]'
How to get the right values when I convert hex to ascii character
I'm trying to convert a hexa file to text, using javascript node js. function hex_to_ascii(str1){ var hex = str1.toString(); var str = ''; for (var n = 0; n < hex.length; n += 2) { str += String.fromCharCode(parseInt(hex.substr(n, 2), 16)); } return str; } I have a problem concening the extended ASCII charaters, so for example when I try to convert 93 I've get “ instead of ô and when I convert FF I've get ÿ instead of (nbsp) space. I want to get the same extended charaters as this table: https://www.rapidtables.com/code/text/ascii-table.html
This problem is slightly more complex than it seems at first, since you need to specify an encoding when converting from extended ascii to a string. For example Windows-1252, ISO-8859-1 etc. Since you wish to use the linked table, I'm assuming you wish to use CP437 encoding. To convert a buffer to string you need a module that will do this for you, converting from a buffer (in a given encoding) to string is not trivial unless the buffer is in a natively supported node.js encoding, e.g. UTF-8, ASCII (7-bit only!), Latin1 etc. I would suggest using the iconv-lite package, this will convert many types of encoding. Once this is installed the code should look as follows (this takes each character from 0x00 to 0xFF and prints the encoded character): const iconv = require('iconv-lite'); function hex_to_ascii(hexData, encoding) { const buffer = Buffer.from(hexData, "hex"); return iconv.decode(buffer, encoding); } const testInputs = [...Array(256).keys()]; const encoding = "CP437"; console.log("Decimal\tHex\tCharacter") for(let input of testInputs) { console.log([input, input.toString(16), hex_to_ascii(input.toString(16), encoding)].join("\t")); }
Arduino: String to int gets strange values
I want to convert a String to an int, and all I could find is that you have to convert the String to a char array and then cast this array to an int, but my code produces strange values and I can't figure out what the problem is. void ledDimm(String command) { // Get the Value xx from string LEDDimm=xx String substring = command.substring(8, command.length()); Serial.println("SubString:"); Serial.println(substring); Serial.println("SubString Length:"); Serial.println(substring.length()); // Create a Char Array to Store the Substring for conversion char valueArray[substring.length() + 1]; Serial.println("sizeof ValueArray"); Serial.println(sizeof(valueArray)); // Copy the substring into the array substring.toCharArray(valueArray, sizeof(valueArray)); Serial.println("valueArray:"); Serial.println(valueArray); // Convert char array to an int value int value = int(valueArray); Serial.println("Integer Value:"); Serial.println(value); // Write the Value to the LEDPin analogWrite(LEDPin, value); } And the serial output looks like this: Received packet of size 11 From 192.168.1.4, port 58615 Contents: LEDDimm=100 SubString: 100 SubString Length: 3 sizeof ValueArray 4 valueArray: 100 Integer Value: 2225 I expected to get an int with the value of 100 but the actual int is 2225?! What have I done wrong here?
There is even an (undocumented) toInt() method in the String class: int myInt = myString.toInt();
You need to use the function int value = atoi(valueArray); where valueArray is a null terminated string.
The toInt () method is very useful in this aspect, but I found that it is able to convert only strings of length five or less, especially a value less than 65535 as its the maximum value int can take. Over this value, it just gives random numbers (overflowing values). Please be aware of this when you use this method as it killed a lot of my useful time to figure this out. Hope it helps.
how to convert hexadecimal from string in c#
i have a string which contains hexadecimal values i want to know how to convert that string to hexadecimal using c#
There's several ways of doing this depending on how efficient you need it to be. Convert.ToInt32(value, fromBase) // ie Convert.ToInt32("FF", 16) == 255 That is the easy way to convert to an Int32. You can use Byte, Int16, Int64, etc. If you need to convert to an array of bytes you can chew through the string 2 characters at a time parsing them into bytes. If you need to do this in a fast loop or with large byte arrays, I think this class is probably the fastest way to do it in purely managed code. I'm always open to suggestions for how to improve it though.
Given the following formats 10A 0x10A 0X10A Perform the following. public static int ParseHexadecimalInteger(string v) { var r = 0; if (!string.IsNullOrEmpty(v)) { var s = v.ToLower().Replace("0x", ""); var c = CultureInfo.CurrentCulture; int.TryParse(s, NumberStyles.HexNumber, c, out r); } return r; }