Conversion problem

hi all,
I need to convert an integer to hex. for example 30>>>1E,
but my problem is that i want the notation 0x1E.



 
 unsigned char Wris[] = {0x8b, a1, a2, a3, a4, 0x10, 0x28};


where a1...a4 are my integer converted.

how can I do?
When you do "conversion" from one base to another, in your case base 10 to base 16, all that changes is how you display the value.

The value itself does not change. For example:
8510 == 5516 == 10101012

The numbers above represent the same value, but in different bases.

So to "convert" your integers, you don't actually need to change their values, all you need to do is change how you display them. For this, use std::hex.

http://www.cplusplus.com/reference/ios/hex/

1
2
3
4
5
6
#include <iostream>

int main()
{
    std::cout << std::hex << 30 << std::endl;
}
1e


Thanks Catfish!
i know... but in my case
unsigned char Wris[] = {0x8b, a1, a2, a3, a4, 0x10, 0x28}; is a bluetooth command ... and if i put a1 a2 .. ecc in integer rappresentation does not work, but if I replace them with the corresponding hex rappresentation 0x1E ecc work fine.
Can you give more code please, to see how you declared a1, a2, etc.?
And to see what works and what doesn't?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 int address = 57856;
 int i=0;

stringstream ss4;
ss4 << hex << address;
string result = ss4.str();

unsigned int a1 = strtoul(("1"+result.substr(0, 1)).c_str(), NULL, 16);
unsigned int a2 = strtoul(("1"+result.substr(1, 1)).c_str(), NULL, 16);
unsigned int a3 = strtoul(("1"+result.substr(2, 1)).c_str(), NULL, 16);
unsigned int a4 = strtoul(("1"+result.substr(3, 1)).c_str(), NULL, 16);

	
unsigned char Wrisultato[] = {0x8b, a1, a2, a3, a4, 0x10, 0x28};

write(fd,(char*)Wrisultato,sizeof(Wrisultato));
In my opinion, this is a clumsy method to split the address into bytes.

How about another way:

1
2
3
4
5
const unsigned char *bytes = reinterpret_cast<unsigned char *> (&address);

unsigned char Wrisultato[] = {0x8b, bytes[0], bytes[1], bytes[2], bytes[3], 0x10, 0x28};
// or maybe
unsigned char Wrisultato[] = {0x8b, bytes[3], bytes[2], bytes[1], bytes[0], 0x10, 0x28};


I am not totally sure what you want to achieve, so maybe my suggestion is wrong.
For example I don't understand why you prefix elements with "1".
ok was my fault here,
1
2
3
4
unsigned int a1 = strtoul(("1"+result.substr(0, 1)).c_str(), NULL, 16);
unsigned int a2 = strtoul(("2"+result.substr(1, 1)).c_str(), NULL, 16);
unsigned int a3 = strtoul(("1"+result.substr(2, 1)).c_str(), NULL, 16);
unsigned int a4 = strtoul(("2"+result.substr(3, 1)).c_str(), NULL, 16);


now work fine but i have another problem, the bluetooth return me a unsigned char buffer of 24 byte .. how can convert that byte in integer?


thanks CAT!
Topic archived. No new replies allowed.