char and hex

hi

did any one know how can i fill a char table with hexadecimal number to be read after byte by byte

i find the exemple in c language :

char y[256] = "\x11\x11\x20\x20";
when i make std::cout << y[0] ; i got 11
So waht is the solution for c++?

thanks
1
2
3
4
5
6
7
8
#include <iostream>
using namespace std;

int main()
{
	char y[256] = "\x11\x11\x20\x20";
	cout << (int)y[0] << endl;
}


When I run this, I get "17", which is what I would expect. Without the int cast, I get a funny character representing ASCII value 17 (0x11).
now, if i have :
a= 0x11;
b= 0x20;

how can i make them in the char table to be read after byte by byte ?

and thank you :)
I'm not sure what you mean by "after byte by byte". You can always insert them into the array after the ones you populated with y[4]=a; y[5]=b;

If you mean adding them after the end of the defined array at indeces 256 and 257, you need to use std::vector.

http://cplusplus.com/reference/stl/vector/

If you don't mean either of these things, then I don't know what you are asking.

Edit: It would probably be good to learn to use std::vector either way.
Last edited on
lets take an other example :

if a have :

x = 0xc123;
i want to make it in a char table y[256]
and when i make std::cout << y[0]; i got 193 ( 0xc1)
so how can i make it in the char table to be read like that ?
Are you looking to convert a sequence of bytes that correspond to the big-endian notation of some integer to that integer?

Write a conversion function, or use the appropriate function from the ntoh* family if your OS provides that.

Something like (assuming y is a vector of bytes of course)
1
2
3
   uint16_t x;
   for(size_t n=0; n < y.size(); ++n)   // std::accumulate() also works
       x = (x << CHAR_BIT) | y[n];

or, with ntohs (tested on Linux (little-endian), Solaris, and AIX (big-endian))

1
2
3
    uint16_t x;
    std::copy(y.begin(), y.end(), reinterpret_cast<char*>(&x));
    x = ntohs(x);
Last edited on
Topic archived. No new replies allowed.