Convert hexadecimal string with leading 0x to signed short in C++?
Have you considered sscanf
with the "%hx" conversion qualifier?
C++ convert hex string to signed integer
use std::stringstream
unsigned int x;
std::stringstream ss;
ss << std::hex << "fffefffe";
ss >> x;
the following example produces -65538
as its result:
#include <sstream>
#include <iostream>
int main() {
unsigned int x;
std::stringstream ss;
ss << std::hex << "fffefffe";
ss >> x;
// output it as a signed type
std::cout << static_cast<int>(x) << std::endl;
}
In the new C++11 standard, there are a few new utility functions which you can make use of! specifically, there is a family of "string to number" functions (http://en.cppreference.com/w/cpp/string/basic_string/stol and http://en.cppreference.com/w/cpp/string/basic_string/stoul). These are essentially thin wrappers around C's string to number conversion functions, but know how to deal with a std::string
So, the simplest answer for newer code would probably look like this:
std::string s = "0xfffefffe";
unsigned int x = std::stoul(s, nullptr, 16);
NOTE: Below is my original answer, which as the edit says is not a complete answer. For a functional solution, stick the code above the line :-).
It appears that since lexical_cast<>
is defined to have stream conversion semantics. Sadly, streams don't understand the "0x" notation. So both the boost::lexical_cast
and my hand rolled one don't deal well with hex strings. The above solution which manually sets the input stream to hex will handle it just fine.
Boost has some stuff to do this as well, which has some nice error checking capabilities as well. You can use it like this:
try {
unsigned int x = lexical_cast<int>("0x0badc0de");
} catch(bad_lexical_cast &) {
// whatever you want to do...
}
If you don't feel like using boost, here's a light version of lexical cast which does no error checking:
template<typename T2, typename T1>
inline T2 lexical_cast(const T1 &in) {
T2 out;
std::stringstream ss;
ss << in;
ss >> out;
return out;
}
which you can use like this:
// though this needs the 0x prefix so it knows it is hex
unsigned int x = lexical_cast<unsigned int>("0xdeadbeef");
Convert a hexadecimal string to an integer efficiently in C?
You want strtol
or strtoul
. See also the Unix man page
C++ hex string to unsigned int
output with int with %u
instead of %d
How to convert a string of hex values to a string?
int len = hex.length();
std::string newString;
for(int i=0; i< len; i+=2)
{
std::string byte = hex.substr(i,2);
char chr = (char) (int)strtol(byte.c_str(), null, 16);
newString.push_back(chr);
}
Write hexadecimal values into register with leading zeros
The only wrong thing I can see in your code is conversion. I think you should have avoided the String to Short
conversion especially when, you can directly convert hex to byte
.
You should have done it something like this -
String[] advanceByte = { "00", "00", "00", "00", "07", "46", "46", "07", "01", "00", "02", "02", "02", "03", "00", "00"};
byte[] byteData = new byte[16];
for (int i = 0; i < advanceByte.length; i++) {
byteData[i] = Byte.parseByte(advanceByte[i],16);
}
for (int i = 0; i < byteData.length - 1;) {
byte[] byteArr1 = {(byte) byteData[i], (byte) byteData[i + 1]};
try {
trans = new ModbusSerialTransaction(serialConnection);
SimpleRegister myregister;
myregister = new SimpleRegister(byteArr1[0], byteArr1[1]);
writeSingleRegisterRequest = new WriteSingleRegisterRequest();
writeSingleRegisterRequest.setUnitID(slave_Address);
writeSingleRegisterRequest.setHeadless();
writeSingleRegisterRequest.setReference(ref2); //register number
myregister.setValue(byteArr1);
Register[] register = {myregister};
writeSingleRegisterRequest.setRegister(myregister);
trans.setRequest(writeSingleRegisterRequest);
trans.execute();
i = i + 2;
ref2++;
} catch (com.ghgande.j2mod.modbus.ModbusException exception) {
advancedStatus = false;
System.out.println("Table 4x4 data Writing Exception");
System.out.println("Exception Occured ----" + exception);
}
serialConnection.close();
}
Integer to hex string in C++
Use <iomanip>
's std::hex
. If you print, just send it to std::cout
, if not, then use std::stringstream
std::stringstream stream;
stream << std::hex << your_int;
std::string result( stream.str() );
You can prepend the first <<
with << "0x"
or whatever you like if you wish.
Other manips of interest are std::oct
(octal) and std::dec
(back to decimal).
One problem you may encounter is the fact that this produces the exact amount of digits needed to represent it. You may use setfill
and setw
this to circumvent the problem:
stream << std::setfill ('0') << std::setw(sizeof(your_type)*2)
<< std::hex << your_int;
So finally, I'd suggest such a function:
template< typename T >
std::string int_to_hex( T i )
{
std::stringstream stream;
stream << "0x"
<< std::setfill ('0') << std::setw(sizeof(T)*2)
<< std::hex << i;
return stream.str();
}
Read hex text format 0x from stream
A solution is to read the value using an unsigned int
then convert to unsigned char
:
unsigned int value;
inp >> hex >> value;
unsigned char byte;
byte = value & 0xFF;
I guess there is something about the type unsigned char
that is causing the issue.
Any C++ language lawyers can quote a section that describes this behavior?
Related Topics
Conditional Compilation Based on Template Values
Is "Long Long" = "Long Long Int" = "Long Int Long" = "Int Long Long"
Is There 'Byte' Data Type in C++
C++ Abstract Class: Constructor Yes or No
Is There a Case Where Including the Same Header Twice Is Actually Helpful
Specifying a Concept for a Type That Has a Member Function Template Using Concepts Lite
Why Isn't "0F" Treated as a Floating Point Literal in C++
Better Variable Exploring When Debugging C++ Code with Eclipse/Cdt
Is There a More Efficient Implementation for a Bidirectional Map
To Stl or !Stl, That Is the Question
How and When to Align to Cache Line Size
What's the Difference Between Sockaddr, Sockaddr_In, and Sockaddr_In6
How to Make an Application Thread Safe
How to Develop Static for Loop in C++
How to Tokenize (Words) Classifying Punctuation as Space
Difference Between Size_T and Std::Size_T
How to Convert Concatenated Strings to Wide-Char with the C Preprocessor