开发者

How to convert fom string to hexadecimal?

I have the following string: s="80". I need to put this in an unsigned char k[]. The unsigned char should look like this: unsigned char k[]={0x38,0x34}, where 0x38=8 and 0x34=0 These are the hexadecimal values for 8 and 0开发者_高级运维. How to do this? Need some help!

Please give some code. Thx

I am working on ubuntu c++ code. THX!

I use this for an encryption! I need 0x38 in an unsigned char.PLEASE HELP! Need some code:)

EDIT:

HOW TO OBTAIN THE DEC/CHAR VALUE AND PUT IT IN AN unsigned char k[]? I've realised that it's ok if in the unsigned char [] i have the dec values {56,52} of the 8 and 0 that i have in the string!


Assuming you want this string converted as ASCII (or UTF-8) it is already in the correct format.

std::string  s="80";

std::cout << "0x" << std::hex << static_cast<int>(s[0]) << "\n";
std::cout << "0x" << std::hex << static_cast<int>(s[1]) << "\n";

If you want it in an int array, then just copy it:

int   data[2];
std::copy(s.begin(), s.end(), data);


I think that no matter you store '8' or 0x39, they will be present as the same binary numbers by the computer.


I think you do not really understand what you are asking.

The following are synonyms:

std::string s = "\x38\x30";
std::string s = "80";

As the following are synonyms:

char c = '8',  s = '0' ;
char c = s[0], s = s[1];
char c = 0x38, s = 0x30;

It is exactly the same (except if your base encoding is not ASCII). This is not an encryption.


std::string s = "80";
unsigned char * pArray = new unsigned char[ s.size() ];

const char * p = s.c_str();
unsigned char * p2 = pArray;

while( *p )
   *p2++ = *p++;

delete []pArray;


You can try it. I did not write these codes. I found I like you

#include <algorithm>
#include <sstream>
#include <iostream>
#include <iterator>
#include <iomanip>

namespace {
   const std::string test="mahmutefe";
}

int main() {
   std::ostringstream result;
   result << std::setw(2) << std::setfill('0') << std::hex << std::uppercase;
   std::copy(test.begin(), test.end(), std::ostream_iterator<unsigned int>(result, " "));
   std::cout << test << ":" << result.str() << std::endl;
   system("PAUSE");
}


convert that string to a char array, then subrtact '0' from each char.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜