Let's suppose I have a string str which consists of characters default to hexadecimal system (0-9, a-f):
string str="1234567890abcdef";
I also have an empty array of n-length (n is known):
unsigned char arr[n]
What I would like to do is fill my array arr with values of str but in a specific manner shown below:
unsigned char arr[8] = {0x12U, 0x34U, 0x56U, 0x78U, 0x90U, 0xabU, 0xcdU, 0xefU};
As it is presented the string str was divided into smaller hexadecimal chars. How can I achieve it? The algorithm for seperation is simple, but I can't figure out how to change string to unsigned char and how to add 0x at the beginning and U at the e开发者_如何学运维nd of the chars.
Your requirements are somewhat unclear. Does the following program perform the action you desire?
#include <string>
#include <iostream>
#include <cstdio>
#include <iterator>
#include <algorithm>
void str2bin(const std::string& in, unsigned char out[])
{
const char* data = in.data();
const std::string::size_type size = in.size();
for(std::string::size_type i = 0; i < size; i+= 2) {
unsigned int tmp;
std::sscanf(data+i, "%02X", &tmp);
out[i/2] = tmp;
}
}
int main() {
unsigned char arr[8];
str2bin("1234567890abcdef", arr);
std::cout << std::hex;
std::copy(arr, arr+8, std::ostream_iterator<unsigned int>(std::cout, ", "));
std::cout << "\n";
}
0x12U
is acually an unsigned int
, not a char
. It just happens to fit in a char. Most importantly, it's a literal that's only used by the compiler. Once in memory, numbers all become binary - series of bits.
In this case, you have a string that contains hexadecimal numbers. I.e. each char represents just 4 bits. You'll need to parse that. a simple function would be sscanf
. The format specifier %2X
reads two hex characters and stores them in a single int. Therefore, you could use "%2X%2X%2X%2X%2X%2X%2X%2X"
to read 8 integers, and then copy each of them to the corresponding unsigned char
.
You might also consider the delimited list builder pattern if you need a less specific version.
精彩评论