I have this:
uint8_t key[] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31};
How can I convert it to char or something so that I can read its contents? this is a key i used to encrypt my data using AES.
Help is appreciated.
Thanks
String converter(uint8_t *str){
return String((char *)str);
}
If I have understood correctly you need something like the following
#include <iostream>
#include <string>
#include <numeric>
#include <iterator>
#include <cstdint>
int main()
{
std::uint8_t key[] =
{
0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31
};
std::string s;
s.reserve( 100 );
for ( int value : key ) s += std::to_string( value ) + ' ';
std::cout << s << std::endl;
}
The program output is
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
You can remove blanks if you not need them.
Having the string you can process it as you like.
If the goal is to construct a string of 2-character hex values, you can use a string stream with IO manipulators like this:
std::string to_hex( uint8_t data[32] )
{
std::ostringstream oss;
oss << std::hex << std::setfill('0');
for( uint8_t val : data )
{
oss << std::setw(2) << (unsigned int)val;
}
return oss.str();
}
This requires the headers:
<string>
<sstream>
<iomanip>
#include <sstream> // std::ostringstream
#include <algorithm> // std::copy
#include <iterator> // std::ostream_iterator
#include <iostream> // std::cout
int main(){
uint8_t key[] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31};
std::ostringstream ss;
std::copy(key, key+sizeof(key), std::ostream_iterator<int>(ss, ","));
std::cout << ss.str();
return 0;
}
0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,
30,31,
You can use a stringstream:
#include <sstream>
void fnPrintArray (uint8_t key[], int length) {
stringstream list;
for (int i=0; i<length; ++i)
{
list << (int)key[i];
}
string key_string = list.str();
cout << key_string << endl;
}
Related
I want to store the hex values into a string, but I don't know to do that when my string is not giving me the hex values when it is printed out. I'm pretty sure it has something to do with hex, but I don't know how to get those int values that print out the correct hex values to be stored into a string without it being changed.
I tried different ways of manipulating this and searched on the web but have not found much of a solution in solving this.
#include <iostream>
#include <string>
#include <sstream>
#include <iterator>
#include <iomanip>
#include <vector>
#include <stdlib.h>
using std::cout;
using std::endl;
using std::string;
using std::hex;
using std::stringstream;
using namespace std;
int main(){
string s2 = "HelloWorld";
cout << "string: " << s2 << endl;
cout << "hexval: ";
vector<int> character; // converting each character to its ascii value
string bytes;
for(int i = 0; i < s2.size(); i++) {
character.push_back(int(s2[i]));
bytes = to_string(character.at(i));
cout << hex << character.at(i) << " ";
cout << bytes << endl;
}
cout << endl;
cout << bytes << endl;
return 0;
}
Here is the output that 'bytes' my string is printing out:
48 72
65 101
6c 108
6c 108
6f 111
57 87
6f 111
72 114
6c 108
64 100
Left is the hexadecimals and right is the string. Two different values. How can I store these hexadecimals that is being converted from a string be stored into a string as a hexadecimal value?
I see 2 different ways:
The first one uses a char array and writes to it with sprintf with %X.
The second way uses a stringstream and streams the int values into it with the hex specifier. You can get the string with the .str() method of stringstream.
#include <iostream>
#include <string>
#include <sstream>
#include <iterator>
#include <iomanip>
#include <vector>
#include <stdlib.h>
using std::cout;
using std::endl;
using std::string;
using std::hex;
using std::stringstream;
using namespace std;
int main(){
string s2 = "HelloWorld";
cout << "string: " << s2 << endl;
string result;
for(int i = 0; i < s2.size(); i++) {
char buffer[20];
sprintf(buffer, "%X ", s2[i]);
result += buffer;
}
cout << "hexval1: " << result << endl;
stringstream res;
for (int val : s2)
res << hex << val << " ";
cout << "hexval2: " << res.str() << endl;
return 0;
}
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.
This question already has answers here:
How to parse a string to an int in C++?
(17 answers)
c++ parse int from string [duplicate]
(5 answers)
Closed 8 years ago.
I wanted to know how I can grab numbers out of a string in C++. I'm getting the string from an input and will be getting multiple lines, but I already have the line reading working.
Note: the lines always have an even number of ints
Here's what I'd like the code to look something like:
std::getline(std::cin, line);// line looks something like "10 3 40 45 8 12"
int a, b;
while(!line.empty() /*line still has ints to extract*/) {
a = someMethod(line);//gets first int. So, 10 first loop, 40 second, 8 third
b = someMethod(line);//gets second int. So, 3 first loop, 45 second, 12 third
myMethod(a,b);//a method from elsewhere in my code. It's here so you know that I need both a and b
}
Anything similar would help. Thank you very much!
Here is a complete example.
#include <sstream>
#include <string>
#include <iostream>
int main(){
std::string line = "2 4 56 6";
std::stringstream stream(line);
int i;
while (stream >> i) {
std::cout << i << std::endl;
}
}
The following works fine also, so reading multiple lines should not be a problem.
#include <sstream>
#include <string>
#include <iostream>
int main(){
std::string line = "2 4 56 6";
std::stringstream stream(line);
int i;
while (stream >> i) {
std::cout << i << std::endl;
}
line = "32 62 44 6 22 58 34 60 71 86";
stream.clear();
stream.str(line);
int a,b;
while(stream >> a && stream >> b){
std::cout << a << " " << b << "\n";
}
}
Get tokens from string line and use them as you want.
#include <iostream>
#include <string>
#include <boost/tokenizer.hpp>
using namespace std;
typedef boost::tokenizer<boost::char_separator<char> >
tokenizer;
void myMethod(int a, int b)
{
cout<<a<<" "<<b<<endl;
}
void getNumber(string line)
{
boost::char_separator<char> sep(" ");
tokenizer tokens(line, sep);
string evenStr, oddStr;
for(tokenizer::iterator iterToken=tokens.begin();
iterToken != tokens.end(); ++iterToken)
{
evenStr = *iterToken;
++iterToken;
if(iterToken != tokens.end())
{
oddStr = *iterToken;
myMethod(atoi(evenStr.c_str()), atoi(oddStr.c_str()));
}
}
}
int main()
{
string line("10 3 40 45 8 12");
getNumber(line);
return 0;
}
You can do like this:
string line;
getline(std::cin, line);// line looks something like "10 3 40 45 8 12"
int a, b;
vector<string> tokens;
istringstream iss(line);
copy(istream_iterator<string>(iss),
istream_iterator<string>(),
back_inserter<vector<string> >(tokens));
stringstream s;
for (int i=0;i<tokens.size()/2;i++)
{
s<< tokens[i];
s>>a;
s.clear();
s<<tokens[i+2];
s>>b;
s.clear();
myMethod(a,b);
}
There are multiple ways to achieve this. I prefer to use boost.
Example:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
int main()
{
std::string line = "10 3 40 45 8 12 9"; //std::getline(std::cin, line);// line looks something like "10 3 40 45 8 12"
std::vector<std::string> intNumbers;
std::string s;
boost::split(intNumbers, line, boost::is_any_of(" "), boost::token_compress_on);
unsigned int i=0;
while(i < intNumbers.size())
{
try{
int a = boost::lexical_cast<int>(intNumbers[i++]);
if(i >= intNumbers.size())
{
std::cout << "invlaid values" << std::endl;
break;
}
int b = boost::lexical_cast<int>(intNumbers[i++]);
std::cout << "value a: " << a << std::endl;
std::cout << "value b: " << b << std::endl;
std::cout << "my method (multiply) a*b: " << (a*b) << std::endl;
}
catch(boost::bad_lexical_cast &e)
{
std::cout << "invlaid values" << std::endl;
}
}
}
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';
}
I am looking for a fastest way to convert a byte array of arbitrary length to a hexadecimal string. This question has been fully answered here at StackOverflow for C#. Some solutions in C++ can be found here.
Are there any "turnkey" or "ready-made" solutions to a problem? C-style solutions are welcome.
#include <vector>
#include <iostream>
#include <algorithm>
#include <string>
#include <iterator>
#include <sstream>
#include <iomanip>
int main()
{
std::vector<unsigned char> v;
v.push_back( 1 );
v.push_back( 2 );
v.push_back( 3 );
v.push_back( 4 );
std::ostringstream ss;
ss << std::hex << std::uppercase << std::setfill( '0' );
std::for_each( v.cbegin(), v.cend(), [&]( int c ) { ss << std::setw( 2 ) << c; } );
std::string result = ss.str();
std::cout << result << std::endl;
return 0;
}
Or, if you've got a compiler that supports uniform initialization syntax and range based for loops you can save a few lines.
#include <vector>
#include <sstream>
#include <string>
#include <iostream>
#include <iomanip>
int main()
{
std::vector<unsigned char> v { 1, 2, 3, 4 };
std::ostringstream ss;
ss << std::hex << std::uppercase << std::setfill( '0' );
for( int c : v ) {
ss << std::setw( 2 ) << c;
}
std::string result = ss.str();
std::cout << result << std::endl;
}
Use boost::alogorithm::hex
std::vector<unsigned char> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
v.push_back(4);
std::string res;
boost::algorithm::hex(v.begin(), v.end(), back_inserter(res));
You can use the C++ Standard Library and or you can use boost::lexical_cast
#include <iostream>
#include <string>
#include <array>
#include <vector>
#include <sstream>
#include <iomanip>
#include <algorithm>
using namespace std;
// use this macro for c++11 feature
#define USE_CPP11
int main(int argc, char* argv[])
{
array<unsigned char, 3> hexArr = {0x01, 0xff, 0x55};
const char separator = ' '; // separator between two numbers
ostringstream os;
os << hex << setfill('0'); // set the stream to hex with 0 fill
#ifdef USE_CPP11
std::for_each(std::begin(hexArr), std::end(hexArr), [&os, &separator] (int i)
{
os << setw(2) << i << separator;
});
#else // c++03
typedef array<unsigned char, 3>::const_iterator const_iterator;
for (const_iterator it = hexArr.begin(); it != hexArr.end(); ++it)
{
os << setw(2) << int(*it) << separator;
}
#endif
os << dec << setfill(' '); // reset the stream to "original"
// print the string
cout << "the string array is: " << os.str() << endl;
return EXIT_SUCCESS;
}
One of the fastest way I know in C++ 11:
template <size_t byteCount>
string BytesArrayToHexString( const std::array<byte, byteCount>& src )
{
static const char table[] = "0123456789ABCDEF";
std::array<char, 2 * byteCount + 1> dst;
const byte* srcPtr = &src[0];
char* dstPtr = &dst[0];
for (auto count = byteCount; count > 0; --count)
{
unsigned char c = *srcPtr++;
*dstPtr++ = table[c >> 4];
*dstPtr++ = table[c & 0x0f];
}
*dstPtr = 0;
return &dst[0];
}
A good compiler should not have any problem to apply SSE optimization on this....