If all you need to do is print the values, then you do not need to do any conversion. Just use printf %.2xon the original array.
int main (void) {
int i;
unsigned char key[16] = "1234567812345678";
for(i = 0; i < 16; i++)
printf("%.2x", key[i]);
return 0;
}
Even if you want to use the array in some other function, the actual bytes stored in key are the ascii characters, i.e. 0x31 0x32 etc. You can generally directly use the array key
Edit: To store the output in a character array, you can use the sprintf function.
char hex[33];
for(i = 0; i < 16; i++)
sprintf(hex+2*i, "%.2x", key[i]);
Also note that the original array key should be 17 bytes to account for the \0 at the end.
If all you need to do is print the values, then you do not need to do any conversion. Just use printf %.2xon the original array.
int main (void) {
int i;
unsigned char key[16] = "1234567812345678";
for(i = 0; i < 16; i++)
printf("%.2x", key[i]);
return 0;
}
Even if you want to use the array in some other function, the actual bytes stored in key are the ascii characters, i.e. 0x31 0x32 etc. You can generally directly use the array key
Edit: To store the output in a character array, you can use the sprintf function.
char hex[33];
for(i = 0; i < 16; i++)
sprintf(hex+2*i, "%.2x", key[i]);
Also note that the original array key should be 17 bytes to account for the \0 at the end.
Here is my take on it - the phex() function converts any data
in memory into a newly allocated string containing the hex representation.
The main() function shows an example usage. The output is "31323334353637383930" for the example data.
#include <stdlib.h> /* malloc() */
#include <stdio.h> /* sprintf() */
#include <string.h> /* strlen(), in the example main() */
/*
* Return a hex string representing the data pointed to by `p`,
* converting `n` bytes.
*
* The string should be deallocated using `free()` by the caller.
*/
char *phex(const void *p, size_t n)
{
const unsigned char *cp = p; /* Access as bytes. */
char *s = malloc(2*n + 1); /* 2*n hex digits, plus NUL. */
size_t k;
/*
* Just in case - if allocation failed.
*/
if (s == NULL)
return s;
for (k = 0; k < n; ++k) {
/*
* Convert one byte of data into two hex-digit characters.
*/
sprintf(s + 2*k, "%02X", cp[k]);
}
/*
* Terminate the string with a NUL character.
*/
s[2*n] = '\0';
return s;
}
/*
* Sample use of `phex()`.
*/
int main(void)
{
const char *data = "1234567890"; /* Sample data */
char *h = phex(data, strlen(data)); /* Convert to hex string */
if (h != NULL)
puts(h); /* Print result */
free(h); /* Deallocate hex string */
return 0;
}
You are confused about the fuctionality of strtol. If you have a string that represents a number in hex, you can use strtol like you have:
char s[] = "ff2d";
int n = strtol(s, NULL, 16);
printf("Number: %d\n", n);
When you want to print the characters of a string in hex, use %x format specifier for each character of the string.
char s[] = "Hello";
char* cp = s;
for ( ; *cp != '\0'; ++cp )
{
printf("%02x", *cp);
}
Use %x flag to print hexadecimal integer
example.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char *string = "hello", *cursor;
cursor = string;
printf("string: %s\nhex: ", string);
while(*cursor)
{
printf("%02x", *cursor);
++cursor;
}
printf("\n");
return 0;
}
output
$ ./example
string: hello
hex: 68656c6c6f
reference
- printf reference
- ascii table
Supposing data is a char*. Working example using std::hex:
for(int i=0; i<data_length; ++i)
std::cout << std::hex << (int)data[i];
Or if you want to keep it all in a string:
std::stringstream ss;
for(int i=0; i<data_length; ++i)
ss << std::hex << (int)data[i];
std::string mystr = ss.str();
Here is something:
char const hex_chars[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
string result = "";
for( int i = 0; i < data_length; ++i )
{
char const byte = data[i];
result += hex_chars[ ( byte & 0xF0 ) >> 4 ];
result += hex_chars[ ( byte & 0x0F ) >> 0 ];
}
You can't fit 5 bytes worth of data into a 4 byte array; that leads to buffer overflows.
If you have the hex digits in a string, you can use sscanf() and a loop:
#include <stdio.h>
#include <ctype.h>
int main()
{
const char *src = "0011223344";
char buffer[5];
char *dst = buffer;
char *end = buffer + sizeof(buffer);
unsigned int u;
while (dst < end && sscanf(src, "%2x", &u) == 1)
{
*dst++ = u;
src += 2;
}
for (dst = buffer; dst < end; dst++)
printf("%d: %c (%d, 0x%02x)\n", dst - buffer,
(isprint(*dst) ? *dst : '.'), *dst, *dst);
return(0);
}
Note that printing the string starting with a zero-byte requires care; most operations terminate on the first null byte. Note that this code did not null-terminate the buffer; it is not clear whether null-termination is desirable, and there isn't enough space in the buffer I declared to add a terminal null (but that is readily fixed). There's a decent chance that if the code was packaged as a subroutine, it would need to return the length of the converted string (though you could also argue it is the length of the source string divided by two).
I would do something like this;
// Convert from ascii hex representation to binary
// Examples;
// "00" -> 0
// "2a" -> 42
// "ff" -> 255
// Case insensitive, 2 characters of input required, no error checking
int hex2bin( const char *s )
{
int ret=0;
int i;
for( i=0; i<2; i++ )
{
char c = *s++;
int n=0;
if( '0'<=c && c<='9' )
n = c-'0';
else if( 'a'<=c && c<='f' )
n = 10 + c-'a';
else if( 'A'<=c && c<='F' )
n = 10 + c-'A';
ret = n + ret*16;
}
return ret;
}
int main()
{
const char *in = "0011223344";
char out[5];
int i;
// Hex to binary conversion loop. For example;
// If in="0011223344" set out[] to {0x00,0x11,0x22,0x33,0x44}
for( i=0; i<5; i++ )
{
out[i] = hex2bin( in );
in += 2;
}
return 0;
}
Assuming ASCII, your example already does contain the values you want them to contain. So you don't have to convert anything. Maybe you want to print them?
This should work:
char hex[255] = {0}; // Varible to hold the hex value
int dec = 1234; // Decimal number to be converted
sprintf(hex,"%X", dec);
printf("%s", hex); // Print hex value
Something very similar:
const char* string_to_hex(const char *str, char *hex, size_t maxlen)
{
static const char* const lut = "0123456789ABCDEF";
if (str == NULL) return NULL;
if (hex == NULL) return NULL;
if (maxlen == 0) return NULL;
size_t len = strlen(str);
char *p = hex;
for (size_t i = 0; (i < len) && (i < (maxlen-1)); ++i)
{
const unsigned char c = str[i];
*p++ = lut[c >> 4];
*p++ = lut[c & 15];
}
*p++ = 0;
return hex;
}
int main()
{
char hex[20];
const char *result = string_to_hex("0123", hex, sizeof(hex));
return 0;
}
Just use the same function for std::string but with char *,
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <string>
using namespace std;
char *string_to_hex(char *input) {
static const char *const lut = "0123456789ABCDEF";
size_t len = strlen(input);
int k = 0;
if (len & 1)
return NULL;
char *output = new char[(len / 2) + 1];
for (size_t i = 0, j = 0; i < len; i++, j += 2) {
const unsigned char c = input[i];
output[j] = lut[c >> 4];
output[j + 1] = lut[c & 15];
}
return output;
}
std::string string_to_hex(const std::string &input) {
static const char *const lut = "0123456789ABCDEF";
size_t len = input.length();
std::string output;
output.reserve(2 * len);
for (size_t i = 0; i < len; ++i) {
const unsigned char c = input[i];
output.push_back(lut[c >> 4]);
output.push_back(lut[c & 15]);
}
return output;
}
int main() {
string test = "Test";
std::string res(string_to_hex(test.c_str()));
cout << res << endl;
res = string_to_hex(test);
cout << res << endl;
}
int flags;
flags = (O << 3) | (C << 2) | (Z << 1) | N;
sprintf(buffer, "0x%02X", 0xff & flags);
flags is defined a single int-variable containing all your flags.
buffer is a char array of sufficient size.
The 0xff & .. is not needed in this case, but might be some day if your flags variable can get negative and you still only want to have a one byte output (2 hex digits).
unsigned char flags = 0; flags = ((O << 3) | (C << 2) | (Z << 1) | N);
now flag contains the Hex value you need.
All you need is parseInt and possibly String.fromCharCode.
parseInt accepts a string and a radix, a.k.a the base you wish to convert from.
console.log(parseInt('F', 16));
String.fromCharCode will take a character code and convert it to the matching string.
console.log(String.fromCharCode(65));
So here's how you can convert C3 into a number and, optionally, into a character.
var input = 'C3';
var decimalValue = parseInt(input, 16); // Base 16 or hexadecimal
var character = String.fromCharCode(decimalValue);
console.log('Input:', input);
console.log('Decimal value:', decimalValue);
console.log('Character representation:', character);
Another simple way is to print "&#" + CharCode like this:
for(var i=9984; i<=10175; i++){
document.write(i + " " + i.toString(16) + " &#" + i + "<br>");
}
OR
for(var i=0x2700; i<=0x27BF; i++){
document.write(i + " " + i.toString(16) + " &#" + i + "<br>");
}
JSFIDDLE