Converting char to int c++ - c++

I'm loosing my mind at the moment and below is what I'm trying to do.
char* buffer;
sprintf(buffer, "0x%08x", 5);
*(int *)(0x834AF2AC + 0x1a) = ?buffer?;
Buffer = 0x05000000
I need to set that in memory, if I just set 05 it will set 0x00000005
Question asked better.
How can I convert an INT into a format of "0x%08x"
So 5 becomes 0x05000000
ANSWERD:
The correct answer is *(int *)(0x834AF2AC + 0x1a) = 5<<24;

Something like this:
#include <iostream> // for std::cout, std::endl
#include <string> // for std::string, std::stoi
int main()
{
std::string s{"0x05"};
int i = std::stoi(s, nullptr, 16); // convert base 16 number in s to int
std::cout << i << std::endl;
}

Two result from google which points to stackoverflow (result 1 and 2).
Convert char to int in C and C++
C char* to int conversion

I'm not sure if I understand correctly but if you want to convert an entire string to int, then I would suggest stringstream.
http://www.cplusplus.com/reference/sstream/stringstream/stringstream/
For hexadecimal string:
#include <string> // std::string
#include <iostream> // std::cout
#include <sstream> // std::stringstream
int main () {
std::stringstream ss;
ss << std::hex << 0x05;
int foo;
ss >> foo;
std::cout << "foo: " << foo << '\n';
return 0;
}

Related

Converting unsigned char * to hexstring

Below code takes a hex string(every byte is represented as its corresponidng hex value)
converts it to unsigned char * buffer and then converts back to hex string.
This code is testing the conversion from unsigned char* buffer to hex string
which I need to send over the network to a receiver process.
I chose hex string as unsigned char can be in range of 0 to 255 and there is no printable character after 127.
The below code just tells the portion that bugs me. Its in the comment.
#include <iostream>
#include <sstream>
#include <iomanip>
using namespace std;
// converts a hexstring to corresponding integer. i.e "c0" - > 192
int convertHexStringToInt(const string & hexString)
{
stringstream geek;
int x=0;
geek << std::hex << hexString;
geek >> x;
return x;
}
// converts a complete hexstring to unsigned char * buffer
void convertHexStringToUnsignedCharBuffer(string hexString, unsigned char*
hexBuffer)
{
int i=0;
while(hexString.length())
{
string hexStringPart = hexString.substr(0,2);
hexString = hexString.substr(2);
int hexStringOneByte = convertHexStringToInt (hexStringPart);
hexBuffer[i] = static_cast<unsigned char>((hexStringOneByte & 0xFF)) ;
i++;
}
}
int main()
{
//below hex string is a hex representation of a unsigned char * buffer.
//this is generated by an excryption algorithm in unsigned char* format
//I am converting it to hex string to make it printable for verification pupose.
//and takes the hexstring as inpuit here to test the conversion logic.
string inputHexString = "552027e33844dd7b71676b963c0b8e20";
string outputHexString;
stringstream geek;
unsigned char * hexBuffer = new unsigned char[inputHexString.length()/2];
convertHexStringToUnsignedCharBuffer(inputHexString, hexBuffer);
for (int i=0;i<inputHexString.length()/2;i++)
{
geek <<std::hex << std::setw(2) << std::setfill('0')<<(0xFF&hexBuffer[i]); // this works
//geek <<std::hex << std::setw(2) << std::setfill('0')<<(hexBuffer[i]); -- > this does not work
// I am not able to figure out why I need to do the bit wise and operation with unsigned char "0xFF&hexBuffer[i]"
// without this the conversion does not work for individual bytes having ascii values more than 127.
}
geek >> outputHexString;
cout << "input hex string: " << inputHexString<<endl;
cout << "output hex string: " << outputHexString<<endl;
if(0 == inputHexString.compare(outputHexString))
cout<<"hex encoding successful"<<endl;
else
cout<<"hex encoding failed"<<endl;
if(NULL != hexBuffer)
delete[] hexBuffer;
return 0;
}
// output
// can some one explain ? I am sure its something silly that I am missing.
the C++20 way:
unsigned char* data = new unsigned char[]{ "Hello world\n\t\r\0" };
std::size_t data_size = sizeof("Hello world\n\t\r\0") - 1;
auto sp = std::span(data, data_size );
std::transform( sp.begin(), sp.end(),
std::ostream_iterator<std::string>(std::cout),
[](unsigned char c) -> std::string {
return std::format("{:02X}", int(c));
});
or if you want to store result into string:
std::string result{};
result.reserve(size * 2 + 1);
std::transform( sp.begin(), sp.end(),
std::back_inserter(result),
[](unsigned char c) -> std::string {
return std::format("{:02X}", int(c));
});
Output:
48656C6C6F20776F726C640A090D00
The output of an unsigned char is like the output of a char which obviously does not what the OP expects.
I tested the following on coliru:
#include <iomanip>
#include <iostream>
int main()
{
std::cout << "Output of (unsigned char)0xc0: "
<< std::hex << std::setw(2) << std::setfill('0') << (unsigned char)0xc0 << '\n';
return 0;
}
and got:
Output of (unsigned char)0xc0: 0�
This is caused by the std::ostream::operator<<() which is chosen out of the available operators. I looked on cppreference
operator<<(std::basic_ostream) and
std::basic_ostream::operator<<
and found
template< class Traits >
basic_ostream<char,Traits>& operator<<( basic_ostream<char,Traits>& os,
unsigned char ch );
in the former (with a little bit help from M.M).
The OP suggested a fix: bit-wise And with 0xff which seemed to work. Checking this in coliru.com:
#include <iomanip>
#include <iostream>
int main()
{
std::cout << "Output of (unsigned char)0xc0: "
<< std::hex << std::setw(2) << std::setfill('0') << (0xff & (unsigned char)0xc0) << '\n';
return 0;
}
Output:
Output of (unsigned char)0xc0: c0
Really, this seems to work. Why?
0xff is an int constant (stricly speaking: an integer literal) and has type int. Hence, the bit-wise And promotes (unsigned char)0xc0 to int as well, yields the result of type int, and hence, the std::ostream::operator<< for int is applied.
This is an option to solve this. I can provide another one – just converting the unsigned char to unsigned.
Where the promotion of unsigned char to int introduces a possible sign-bit extension (which is undesired in this case), this doesn't happen when unsigned char is converted to unsigned. The output stream operator for unsigned provides the intended output as well:
#include <iomanip>
#include <iostream>
int main()
{
std::cout << "Output of (unsigned char)0xc0: "
<< std::hex << std::setw(2) << std::setfill('0') << (unsigned)(unsigned char)0xc0 << '\n';
const unsigned char c = 0xc0;
std::cout << "Output of unsigned char c = 0xc0: "
<< std::hex << std::setw(2) << std::setfill('0') << (unsigned)c << '\n';
return 0;
}
Output:
Output of (unsigned char)0xc0: c0
Output of unsigned char c = 0xc0: c0
Live Demo on coliru

Assign a integer to char pointer using stringstream

I want to assign integer to a char pointer using stringstream. But I am getting error while running this program at line ss >> p. Please help me here i want integer to go into the buffer first and the it must be assigned to a char*.
#include <string> // std::string
#include <iostream> // std::cout
#include <sstream> // std::stringstream
using namespace std;
int main ()
{
stringstream ss;
int n=100;
char *p;
ss << n;
ss >> p; //not working
cout << ss;
return 0;
}
Use stringstream::str to get a C++ string, then use .c_str() on the string:
#include <string> // std::string
#include <iostream> // std::cout
#include <sstream> // std::stringstream
using namespace std;
int main ()
{
stringstream ss;
int n = 100;
char* p;
ss << n;
string tmp = ss.str();
p = const_cast<char*>(tmp.c_str());
cout << "p: " << p << '\n';
return 0;
}
Beware that the char pointer becomes invalid as soon as the string goes out of scope. If you need some kind of factory function behavior, return a string by value, use strlcpy or maybe new and shared_ptr.
#include <string> // std::string
#include <iostream> // std::cout
#include <sstream> // std::stringstream
using namespace std;
int main ()
{
stringstream ss;
int n=100;
char buffer[100];
char *p = buffer;
ss << n;
ss >> p;
cout << p;
return 0;
}
This is fixing only the problem you directly encountered - there's no storage behind p so it will crash. Stylistically there are many other things to improve / fix, but this should show you what part of this was actually wrong.

c++ converting int to char + add leading zeros to char

I got numbers from 0 to 999. How can I achieve the following
int i = 123;//possible values 0-999
char i_char[3] = /*do conversion of int i to char and add 3 leading zeros*/
Example(s): i_char shall look like "001" for i=1, "011" for i=11 or "101" for i=101
Use a std::ostringstream with std::setfill() and std::setw(), eg:
#include <string>
#include <sstream>
#include <iomanip>
int i = ...;
std::ostringstream oss;
oss << std::setfill('0') << std::setw(3) << i;
std::string s = oss.str();
It appears you are looking for sprintf, or perhaps printf.
int i = 123;
char str[10];
sprintf(str, "%03d", i);
Since, you tagged the question with c++ here is a quick solution using std::string and std::to_string:
#include <iostream>
#include <string>
int main() {
int i = 1;
std::string s = std::to_string(i);
if ( s.size() < 3 )
s = std::string(3 - s.size(), '0') + s;
std::cout << s << std::endl;
return 0;
}
For i=1 it will output: 001.

How to convert Byte Array to hex string in visual c++?

Declaration of a method are following:
//some.h
void TDES_Decryption(BYTE *Data, BYTE *Key, BYTE *InitalVector, int Length);
I am calling this method from the following code:
//some.c
extern "C" __declspec(dllexport) bool _cdecl OnDecryption(LPCTSTR stringKSN, LPCTSTR BDK){
TDES_Decryption(m_Track1Buffer, m_cryptoKey, init_vector, len);
return m_Track1Buffer;
}
Where as data type of m_Track1Buffer is BYTE m_Track1Buffer[1000];
Now i want to make some changes in above method i.e. want to return the String in hex instead of Byte. How should i convert this m_Track1buffer to Hex string
As you have mentioned c++, here is an answer. Iomanip is used to store ints in hex form into stringstream.
#include <iomanip>
#include <sstream>
#include <string>
std::string hexStr(const uint8_t *data, int len)
{
std::stringstream ss;
ss << std::hex;
for( int i(0) ; i < len; ++i )
ss << std::setw(2) << std::setfill('0') << (int)data[i];
return ss.str();
}
This code will convert byte array of fixed size 100 into hex string:
BYTE array[100];
char hexstr[201];
int i;
for (i=0; i<ARRAY_SIZE(array); i++) {
sprintf(hexstr+i*2, "%02x", array[i]);
}
hexstr[i*2] = 0;
Here is a somewhat more flexible version (Use uppercase characters? Insert spaces between bytes?) that can be used with plain arrays and various standard containers:
#include <string>
#include <sstream>
#include <iomanip>
template<typename TInputIter>
std::string make_hex_string(TInputIter first, TInputIter last, bool use_uppercase = true, bool insert_spaces = false)
{
std::ostringstream ss;
ss << std::hex << std::setfill('0');
if (use_uppercase)
ss << std::uppercase;
while (first != last)
{
ss << std::setw(2) << static_cast<int>(*first++);
if (insert_spaces && first != last)
ss << " ";
}
return ss.str();
}
Example usage (plain array):
uint8_t byte_array[] = { 0xDE, 0xAD, 0xC0, 0xDE, 0x00, 0xFF };
auto from_array = make_hex_string(std::begin(byte_array), std::end(byte_array), true, true);
assert(from_array == "DE AD C0 DE 00 FF");
Example usage (std::vector):
// fill with values from the array above
std::vector<uint8_t> byte_vector(std::begin(byte_array), std::end(byte_array));
auto from_vector = make_hex_string(byte_vector.begin(), byte_vector.end(), false);
assert(from_vector == "deadc0de00ff");
Using stringstream, sprintf and other functions in the loop is simply not C++. It's horrible for performance and these kind of functions usually get called a lot (unless you're just writing some things into the log).
Here's one way of doing it.
Writing directly into the std::string's buffer is discouraged because specific std::string implementation might behave differently and this will not work then but we're avoiding one copy of the whole buffer this way:
#include <iostream>
#include <string>
#include <vector>
std::string bytes_to_hex_string(const std::vector<uint8_t> &input)
{
static const char characters[] = "0123456789ABCDEF";
// Zeroes out the buffer unnecessarily, can't be avoided for std::string.
std::string ret(input.size() * 2, 0);
// Hack... Against the rules but avoids copying the whole buffer.
auto buf = const_cast<char *>(ret.data());
for (const auto &oneInputByte : input)
{
*buf++ = characters[oneInputByte >> 4];
*buf++ = characters[oneInputByte & 0x0F];
}
return ret;
}
int main()
{
std::vector<uint8_t> bytes = { 34, 123, 252, 0, 11, 52 };
std::cout << "Bytes to hex string: " << bytes_to_hex_string(bytes) << std::endl;
}
how about using the boost library like this (snippet taken from http://theboostcpplibraries.com/boost.algorithm ):
#include <boost/algorithm/hex.hpp>
#include <vector>
#include <string>
#include <iterator>
#include <iostream>
using namespace boost::algorithm;
int main()
{
std::vector<char> v{'C', '+', '+'};
hex(v, std::ostream_iterator<char>{std::cout, ""});
std::cout << '\n';
std::string s = "C++";
std::cout << hex(s) << '\n';
std::vector<char> w{'4', '3', '2', 'b', '2', 'b'};
unhex(w, std::ostream_iterator<char>{std::cout, ""});
std::cout << '\n';
std::string t = "432b2b";
std::cout << unhex(t) << '\n';
}

converting from strings to ints

I would like to know what is the easiest way to convert an int to C++ style string and from C++ style string to int.
edit
Thank you very much. When converting form string to int what happens if I pass a char string ? (ex: "abce").
Thanks & Regards,
Mousey
Probably the easiest is to use operator<< and operator>> with a stringstream (you can initialize a stringstream from a string, and use the stream's .str() member to retrieve a string after writing to it.
Boost has a lexical_cast that makes this particularly easy (though hardly a paragon of efficiency). Normal use would be something like int x = lexical_cast<int>(your_string);
You can change "%x" specifier to "%d" or any other format supported by sprintf. Ensure to appropriately adjust the buffer size 'buf'
int main(){
char buf[sizeof(int)*2 + 1];
int x = 0x12345678;
sprintf(buf, "%x", x);
string str(buf);
int y = atoi(str.c_str());
}
EDIT 2:
int main(){
char buf[sizeof(int)*2 + 1];
int x = 42;
sprintf(buf, "%x", x);
string str(buf);
//int y = atoi(str.c_str());
int y = static_cast<int>(strtol(str.c_str(), NULL, 16));
}
This is to convert string to number.
#include "stdafx.h"
#include <iostream>
#include <string>
#include <sstream>
int convert_string_to_number(const std::string& st)
{
std::istringstream stringinfo(st);
int num = 0;
stringinfo >> num;
return num;
}
int main()
{
int number = 0;
std::string number_as_string("425");
number = convert_string_to_number(number_as_string);
std::cout << "The number is " << number << std::endl;
std::cout << "Number of digits are " << number_as_string.length() << std::endl;
}
Like wise, the following is to convert number to string.
#include "stdafx.h"
#include <iostream>
#include <string>
#include <sstream>
std::string convert_number_to_string(const int& number_to_convert)
{
std::ostringstream os;
os << number_to_convert;
return (os.str());
}
int main()
{
int number = 425;
std::string stringafterconversion;
stringafterconversion = convert_number_to_string(number);
std::cout << "After conversion " << stringafterconversion << std::endl;
std::cout << "Number of digits are " << stringafterconversion.length() << std::endl;
}
Use atoi to convert a string to an int. Use a stringstream to convert the other way.