0

how this convertion done from unsigned char* to unsigned short?

#include<iostream>
using namespace std;

int main()
{
    unsigned short x;
    x= (unsigned char*)&x - (unsigned char*) 0x8888;
    cout<<us<<endl;
    return 0;
}

when I am trying to add like this

x= (unsigned char*)&x + (unsigned char*) 0x8888;

Then error comes up. it says "invalid operands of types 'unsigned char*' and 'unsigned char*' to binary 'operator+' " please help me to understand this syntax.

  • 1
    Why are you trying to do this? –  Feb 12 '17 at 19:48
  • There is no conversion from `unsigned char *` to `unsigned short` in your code. The subtraction has higher precedence than the assignment. – M.M Feb 13 '17 at 09:05

2 Answers2

0

Subtraction operation can be performed on two address data type but not addition.
For addition, either both operand of + shall be of arithmetic type or one operand shall be a pointer and other shall be an integer type.

C++11-§ 5.7/1:

For addition, either both operands shall have arithmetic or unscoped enumeration type, or one operand shall be a pointer to a completely-defined object type and the other shall have integral or unscoped enumeration type.

Community
  • 1
  • 1
haccks
  • 104,019
  • 25
  • 176
  • 264
  • Brother this not working x= (unsigned char*)&x + 88 i have changed second operand to int. – Sirazul Islam Feb 12 '17 at 20:19
  • I am trying this code "x= (unsigned char*)&x + 88". Then "error: invalid conversion from 'short unsigned int*' to 'short unsigned int' [-fpermissive]|" – Sirazul Islam Feb 12 '17 at 20:25
  • `(unsigned char*)&x + 88` will give an `unsigned char*` value. `x` is `unsigned short` type. Error/warning is legit. – haccks Feb 12 '17 at 20:27
  • x= (unsigned short*)&x + 88; i changed (unsigned char*) to (unsigned short*) Then "error: invalid conversion from 'short unsigned int*' to 'short unsigned int' [-fpermissive]|" – Sirazul Islam Feb 12 '17 at 20:32
  • Do you know the difference between pointer and `int` data types? – haccks Feb 12 '17 at 20:34
0

You could convert pointer to int/short/long using cstdint C++11 as below, But I'm not certain whether it is advisable to add pointers as mentioned by @haccks

#include<iostream>
#include <cstdint>

using namespace std;

int main()
{
    unsigned short x;
    //x= (unsigned char*)&x + (unsigned char*) 0x8888;
    x = static_cast<unsigned short>(reinterpret_cast<uintptr_t>(&x)) + static_cast<unsigned short>(0x8888);
    cout<<x<<endl;
    return 0;
}

Refer to this link for more information.

Community
  • 1
  • 1
Panch
  • 1,097
  • 3
  • 12
  • 43