int main()
{
char arr[4];
arr[0] = 0x11;
arr[1] = 0xc0;
arr[2] = 0x0c;
arr[3] = 0x00;
size_t len = sizeof(arr) / sizeof(*arr);
char* str = (char*)malloc(len * 2 + 1);
for (size_t i = 0; i < len; i++)
{
const static char table[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c','d','e','f' };
unsigned char c = (unsigned char)(arr[i]);
unsigned int lowbyte = c & 0x0f;
unsigned int highbyte = (c >> 4) & 0x0f;
str[2 * i] = table[highbyte];
str[2 * i + 1] = table[lowbyte];
}
str[2 * len] = '\0';
printf("%s\n",str);
return 0;
}
Answer from selbie on Stack Overflowint main()
{
char arr[4];
arr[0] = 0x11;
arr[1] = 0xc0;
arr[2] = 0x0c;
arr[3] = 0x00;
size_t len = sizeof(arr) / sizeof(*arr);
char* str = (char*)malloc(len * 2 + 1);
for (size_t i = 0; i < len; i++)
{
const static char table[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c','d','e','f' };
unsigned char c = (unsigned char)(arr[i]);
unsigned int lowbyte = c & 0x0f;
unsigned int highbyte = (c >> 4) & 0x0f;
str[2 * i] = table[highbyte];
str[2 * i + 1] = table[lowbyte];
}
str[2 * len] = '\0';
printf("%s\n",str);
return 0;
}
Convert each character to an unsigned character (so the 0xc0 isn't negative), then convert it to an integer and output as a two digit hexadecimal value.
#include <stdlib.h>
#include <stdio.h>
#define INT(x) ((int)(unsigned char)(x))
int main()
{
char arr[4];
arr[0] = 0x11;
arr[1] = 0xc0;
arr[2] = 0x0c;
arr[3] = 0x00;
char *str;
str=malloc(32);
sprintf(str, "%02x%02x%02x%02x",
INT(arr[0]), INT(arr[1]), INT(arr[2]), INT(arr[3]));
puts(str);
}
Output is:
11c00c00
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
javascript - Convert a Char Array to a String - Stack Overflow
Convert a HexaDecimal char array to a Char Array Or String in C - Post.Byes
Char array to hex string C++ - Stack Overflow
Hex String to char* array C++ - Stack Overflow
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;
}
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 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
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;
}
printf("%02X:%02X:%02X:%02X", buf[0], buf[1], buf[2], buf[3]);
For a more generic way:
int i;
for (i = 0; i < x; i++)
{
if (i > 0) printf(":");
printf("%02X", buf[i]);
}
printf("\n");
To concatenate to a string, there are a few ways you can do this. I'd probably keep a pointer to the end of the string and use sprintf. You should also keep track of the size of the array to make sure it doesn't get larger than the space allocated:
int i;
char* buf2 = stringbuf;
char* endofbuf = stringbuf + sizeof(stringbuf);
for (i = 0; i < x; i++)
{
/* i use 5 here since we are going to add at most
3 chars, need a space for the end '\n' and need
a null terminator */
if (buf2 + 5 < endofbuf)
{
if (i > 0)
{
buf2 += sprintf(buf2, ":");
}
buf2 += sprintf(buf2, "%02X", buf[i]);
}
}
buf2 += sprintf(buf2, "\n");
For completude, you can also easily do it without calling any heavy library function (no snprintf, no strcat, not even memcpy). It can be useful, say if you are programming some microcontroller or OS kernel where libc is not available.
Nothing really fancy you can find similar code around if you google for it. Really it's not much more complicated than calling snprintf and much faster.
#include <stdio.h>
int main(){
unsigned char buf[] = {0, 1, 10, 11};
/* target buffer should be large enough */
char str[12];
unsigned char * pin = buf;
const char * hex = "0123456789ABCDEF";
char * pout = str;
int i = 0;
for(; i < sizeof(buf)-1; ++i){
*pout++ = hex[(*pin>>4)&0xF];
*pout++ = hex[(*pin++)&0xF];
*pout++ = ':';
}
*pout++ = hex[(*pin>>4)&0xF];
*pout++ = hex[(*pin)&0xF];
*pout = 0;
printf("%s\n", str);
}
Here is another slightly shorter version. It merely avoid intermediate index variable i and duplicating laste case code (but the terminating character is written two times).
#include <stdio.h>
int main(){
unsigned char buf[] = {0, 1, 10, 11};
/* target buffer should be large enough */
char str[12];
unsigned char * pin = buf;
const char * hex = "0123456789ABCDEF";
char * pout = str;
for(; pin < buf+sizeof(buf); pout+=3, pin++){
pout[0] = hex[(*pin>>4) & 0xF];
pout[1] = hex[ *pin & 0xF];
pout[2] = ':';
}
pout[-1] = 0;
printf("%s\n", str);
}
Below is yet another version to answer to a comment saying I used a "trick" to know the size of the input buffer. Actually it's not a trick but a necessary input knowledge (you need to know the size of the data that you are converting). I made this clearer by extracting the conversion code to a separate function. I also added boundary check code for target buffer, which is not really necessary if we know what we are doing.
#include <stdio.h>
void tohex(unsigned char * in, size_t insz, char * out, size_t outsz)
{
unsigned char * pin = in;
const char * hex = "0123456789ABCDEF";
char * pout = out;
for(; pin < in+insz; pout +=3, pin++){
pout[0] = hex[(*pin>>4) & 0xF];
pout[1] = hex[ *pin & 0xF];
pout[2] = ':';
if (pout + 3 - out > outsz){
/* Better to truncate output string than overflow buffer */
/* it would be still better to either return a status */
/* or ensure the target buffer is large enough and it never happen */
break;
}
}
pout[-1] = 0;
}
int main(){
enum {insz = 4, outsz = 3*insz};
unsigned char buf[] = {0, 1, 10, 11};
char str[outsz];
tohex(buf, insz, str, outsz);
printf("%s\n", str);
}
You are missing the padding in the hex conversion. You'll want to use
function toHexString(byteArray) {
return Array.from(byteArray, function(byte) {
return ('0' + (byte & 0xFF).toString(16)).slice(-2);
}).join('')
}
so that each byte transforms to exactly two hex digits. Your expected output would be 04812d7e3a9829e5d51bdd64ceb35df060699bc1309731bd6e6f1a5443a7f9ce0af4382fcfd6f5f8a08bb2619709c2d49fb771601770f2c267985af2754e1f8cf9
Using map() won't work if the input is of a type like Uint8Array: the result of map() is also Uint8Array which can't hold the results of string conversion.
function toHexString(byteArray) {
var s = '0x';
byteArray.forEach(function(byte) {
s += ('0' + (byte & 0xFF).toString(16)).slice(-2);
});
return s;
}
- Create a loop running until it finds
\0in the input buffer. - For each character number
[i]in the input string, mask out the upper and lower nibble of that byte. Make sure to use unsigned types. - Run each of the two nibbles through a lookup table such as
const char HEX_LOOKUP [16] = "0123456789ABCDEF";, where the value of the nibble is used as index. - Store the result in output index
[i*2]and[i*2+1], since the output will be exactly twice as large as the input. - Null terminate the output string.
If you don't wanna use library functions, you'll have to build a simple lookup table yourself:
#include <stdio.h> // only for printing the result
const char table[] = "0123456789abcdef";
int main(void) {
char src[5 + 1] = "hello";
char dst[5 * 2 + 1];
char *s, *d;
for (s = src, d = dst; *s != '\0'; s++, d += 2) {
const unsigned char lo = *s & 0xf;
const unsigned char hi = *s >> 4;
*d = table[hi];
*(d + 1) = table[lo];
}
*d = '\0';
puts(dst);
return 0;
}