Trying to take a decimal value and convert it to hex. This is a C# script inside SCADA program. Following converts Hex to Dec just fine:
using System;
using MasterSCADA.Script.FB;
using MasterSCADA.Hlp;
using FB;
using System.Linq;
public partial class ФБ : ScriptBase
{
public override void Execute()
{
string hexValue = InVal;
int num = Int32.Parse(hexValue, System.Globalization.NumberStyles.HexNumber);
OutVal = num;
}
}
But I am having problem with the opposite - when I try to convert Dec to Hex. To my understanding the following should work but it gives an error: No overload for method 'ToString' takes '1' arguments in line 12
11 int? decValue = InVal;
12 string hexValue = decValue.ToString("X");
13 //string hexValue = string.Format("{0:F0}", decValue);
14 uint num = uint.Parse(hexValue, System.Globalization.NumberStyles.HexNumber);
15 OutVal = num;
I can avoid the error by using line 13 instead of 12 but in this case I am converting Hex to Dec instead of Dec to Hex. Can anyone help please?
You're trying to call ToString(string) on an int? value. Nullable<T> doesn't have a ToString(string) overload. You need something like:
string hexValue = decValue == null ? "" : decValue.Value.ToString("X");
(Obviously adjust the above depending on what you want the result to be if decValue is null.)
Try decValue.Value.ToString("X");
Your type is int? and not int
Here is my function:
using System;
using System.Collections.Generic;
class DecimalToHexadecimal
{
static string DecToHex(decimal decim)
{
string result = String.Empty;
decimal dec = decim;
while (dec >= 1)
{
var remainer = dec % 16;
dec /= 16;
result = ((int)remainer).ToString("X") + result;
}
return result;
}
static void Main()
{
Console.WriteLine("Enter decimal");
decimal dec = decimal.Parse(Console.ReadLine());
Console.WriteLine("Hexadecimal representation to {0} is {1}", dec, DecToHex(dec));
Console.ReadKey();
}
}
Related
I´ve tried looking up an answer but I was unable to deduct from any of those what exactly the issue here is. When I try to verify it says "Expected "," or "..." before numeric constant" and highlights "#define Odvesna"
#define A1 35
#define B1 15
#define Odvesna 10
#define Prepona 30
int O(int A1, int B1) {
int result;
result = 2*(A1+B1);
return result;
}
int S(int A1,int B1) {
int result;
result = A1*B1;
return result;
}
int St(int Odvesna,int Prepona) {
int result;
result = Prepona*Odvesna/2;
return result;
}
int Ot(int Odvesna,int Prepona) {
int result;
result = sqrt(pow(Odvesna)+pow(Prepona))+ Odvesna+Prepona;
return result;
}
void Vystup(O,S,St) {
Serial.print("O = ");Serial.println(O);
Serial.print("S = ");Serial.println(S);
Serial.print("St = ");Serial.println(St);
Serial.print("Ot = ");Serial.println(Ot);
/*******************SETUP**********************************/
void setup() {
Serial.begin(115200);
Vystup(O,S,St);
}
/**************MAIN PROGRAM********************************/
void loop() {
}
There is a } missing at the end of the Vystup() function.
You can't reuse #define names as variable names.
In this call: Vystup(O,S,St); you are passing function pointers as parameters.
int St(int Odvesna,int Prepona) {} is turned into int St(int 10,int 30) {} by the preprocessor, and the compiler doesn't understand what you mean by that.
You have to use other variable names when you define your functions.
Also, void Vystup(O,S,St) {} won't work; you are passing functions as parameters, not ints as you maybe think.
How to convert from Hex string to ASCII string in JavaScript?
Ex:
32343630 it will be 2460
function hex2a(hexx) {
var hex = hexx.toString();//force conversion
var str = '';
for (var i = 0; i < hex.length; i += 2)
str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
return str;
}
hex2a('32343630'); // returns '2460'
Another way to do it (if you use Node.js):
var input = '32343630';
const output = Buffer.from(input, 'hex');
log(input + " -> " + output); // Result: 32343630 -> 2460
For completeness sake the reverse function:
function a2hex(str) {
var arr = [];
for (var i = 0, l = str.length; i < l; i ++) {
var hex = Number(str.charCodeAt(i)).toString(16);
arr.push(hex);
}
return arr.join('');
}
a2hex('2460'); //returns 32343630
You can use this..
var asciiVal = "32343630".match(/.{1,2}/g).map(function(v){
return String.fromCharCode(parseInt(v, 16));
}).join('');
document.write(asciiVal);
** for Hexa to String**
let input = '32343630';
Note : let output = new Buffer(input, 'hex'); // this is deprecated
let buf = Buffer.from(input, "hex");
let data = buf.toString("utf8");
I found a useful function present in web3 library.
var hexString = "0x1231ac"
string strValue = web3.toAscii(hexString)
Update: Newer version of web3 has this function in utils
The functions now resides in utils:
var hexString = "0x1231ac"
string strValue = web3.utils.hexToAscii(hexString)
I've found that the above solution will not work if you have to deal with control characters like 02 (STX) or 03 (ETX), anything under 10 will be read as a single digit and throw off everything after. I ran into this problem trying to parse through serial communications. So, I first took the hex string received and put it in a buffer object then converted the hex string into an array of the strings like so:
buf = Buffer.from(data, 'hex');
l = Buffer.byteLength(buf,'hex');
for (i=0; i<l; i++){
char = buf.toString('hex', i, i+1);
msgArray.push(char);
}
Then .join it
message = msgArray.join('');
then I created a hexToAscii function just like in #Delan Azabani's answer above...
function hexToAscii(str){
hexString = str;
strOut = '';
for (x = 0; x < hexString.length; x += 2) {
strOut += String.fromCharCode(parseInt(hexString.substr(x, 2), 16));
}
return strOut;
}
then called the hexToAscii function on 'message'
message = hexToAscii(message);
This approach also allowed me to iterate through the array and slice into the different parts of the transmission using the control characters so I could then deal with only the part of the data I wanted.
Hope this helps someone else!
console.log(
"68656c6c6f20776f726c6421".match(/.{1,2}/g).reduce((acc,char)=>acc+String.fromCharCode(parseInt(char, 16)),"")
)
An optimized version of the implementation of the reverse function proposed by #michieljoris (according to the comments of #Beterraba and #Mala):
function a2hex(str) {
var hex = '';
for (var i = 0, l = str.length; i < l; i++) {
var hexx = Number(str.charCodeAt(i)).toString(16);
hex += (hexx.length > 1 && hexx || '0' + hexx);
}
return hex;
}
alert(a2hex('2460')); // display 32343630
I use this one, it seems more clear to me as I also receive data with spaces like '30 31 38 30 38 30' and the output is 018080
hexToString(hex: string): string {
return hex.split(' ').map(s => string.fromCharCode(parseInt(s,16))).join('');
}
I have a string in arduino
String name="apple orange banana";
Is it possible to store each item in an array arr
so that
arr[0]="apple"
arr[1]="orange" ......etc
if not store them in individual variables?
How to split a string using a specific delimiter in Arduino? I believe this would help you, you could do a while loop like:
int x;
String words[3];
while(getValue(name, ' ', x) != NULL){
words[x] = getValue(name, ' ', x);
}
Using this function:
// https://stackoverflow.com/questions/9072320/split-string-into-string-array
String getValue(String data, char separator, int index)
{
int found = 0;
int strIndex[] = {0, -1};
int maxIndex = data.length()-1;
for(int i=0; i<=maxIndex && found<=index; i++){
if(data.charAt(i)==separator || i==maxIndex){
found++;
strIndex[0] = strIndex[1]+1;
strIndex[1] = (i == maxIndex) ? i+1 : i;
}
}
return found>index ? data.substring(strIndex[0], strIndex[1]) : "";
}
If you know your list length and the max characters per list item, you could do
char arr[3][6] = {"apple", "orange", banana"};
edit: if you are looking for something like String arr[3] you aren't going to get it because of how memory is managed with the C language
I want to read a file from an SD card that contains integers. The reading function returns decimal ASCII values between 48 to 57 which corresponds to the characters '0' to '9'. How can I save this character as an integer? This is the code I have now. If I run this code and read '0' from the file, access will be 48 and c as well.
char c;
String chat_id;
int access;
int getaccess(String chat_id) {
String a = "Gebruikers/" + chat_id + ".txt";
if (!SD.exists(a.c_str())) {
return 0;
} else {
myFile = SD.open("Gebruikers/" + chat_id + ".txt");
if (myFile) {
Serial.println("Getting the access number");
access = myFile.read();
myFile.close();
Serial.println("done.");
c = access + 0;
return c;
} else {
Serial.println("error opening " + nummer + ".txt");
}
}
}
If you are reading single digits, then just subtract 48 form the ASCII code and you'll get the number.
Most commonly written as:
int oneDigitNumber = someAsciiCode - '0';
Hi im trying to figure out how to recursively search a tree to find a character and the binary code to get to that character. basically the goal is to go find the code for the character and then write it to a file. the file writer part i can do no problem but the real problem is putting the binary code into a string. while im searching for the character. please help!
this is the code for the recursive method:
public String biNum(Frequency root, String temp, String letter)
{
//String temp = "";
boolean wentLeft = false;
if(root.getString() == null && !wentLeft)
{
if(root.left.getString() == null)
{
temp = temp + "0";
return biNum(root.left, temp, letter);
}
if(root.left.getString().equals(letter))
{
return temp = temp + "0";
}
else
{
wentLeft = true;
temp = temp.substring(0, temp.length() - 1);
return temp;
}
}
if(root.getString() == null && wentLeft)
{
if(root.right.getString() == null)
{
temp = temp + "1";
return (biNum(root.right, temp, letter));
}
if(root.right.getString().equals(letter))
{
return temp = temp + "1";
}
else
{
wentLeft = false;
temp = temp.substring(0, temp.length() - 1);
return temp;
}
}
return temp;
}
and this is the Frequency class:
package huffman;
public class Frequency implements Comparable {
private String s;
private int n;
public Frequency left;
public Frequency right;
private String biNum;
private String leaf;
Frequency(String s, int n, String biNum)
{
this.s = s;
this.n = n;
this.biNum = biNum;
}
public String getString()
{
return s;
}
public int getFreq()
{
return n;
}
public void setFreq(int n)
{
this.n = n;
}
public String getLeaf()
{
return leaf;
}
public void setLeaf()
{
this.leaf = "leaf";
}
#Override
public int compareTo(Object arg0) {
Frequency other = (Frequency)arg0;
return n < other.n ? -1 : (n == other.n ? 0 : 1);
}
}
In your updated version, I think you should re-examine return biNum(root.left, temp, letter);. Specifically, what happens if the root node of the entire tree has a left child which is not a leaf (and thus root.left.getString() == null) but the value you seek descends from the right child of the root node of the entire tree.
Consider this tree, for example:
26
/ \
/ \
/ \
11 15
/ \ / \
/ B A \
6 5 6 9
/ \ / \
D \ C sp
3 3 4 5
/ \
E F
2 1
and trace the steps your function will follow looking for the letter C.
Perhaps you should consider traversing the entire tree (and building up the pattern of 1s and 0s as you go) without looking for any specific letter but taking a particular action when you find a leaf node?