I’m trying to make 128 and 256 bit integers in C++, and noticed casting char** to int* and int* to int (and backwards) can be used to convert char arrays to integers and integers to char arrays.
Also, char* + int works fine.
However, when I try char* + char* the compiler tells me the types are invalid. Is there any workaround for this, or will I have to write my own functions for the operators?
For example:
int32_t intValue = 2147483647;
char *charPointer = *( char** ) &intValue;
charPointer += 2147483647;
charPointer += 2;
cout << ( *( int64_t* ) &charPointer ) << endl;
output: 4294967296
Basically, what I do should be something like the following:
int32_t intValue = 2147483647;
somewhere in memory:
[ 05 06 07 08 09 0A 0B 0C ] ( address, in hex )
[ .. .. FF FF FF 7F .. .. ] ( value, in hex )
then:
char *charPointer = *( char** ) &intValue;
somewhere in memory:
[ 58 59 5A 5B 5C 5D 5E 5F ] ( address, in hex )
[ .. .. 07 00 00 00 .. .. ] ( value, in hex )
then:
charPointer += 2147483647;
I honestly have no idea what happens here.
It seems like it does something like this though:
[ 05 06 07 08 09 0A 0B 0C ] ( address, in hex )
[ .. .. FF FF FF FE .. .. ] ( value, in hex )
then:
charPointer += 2;
Same here.
Something like this:
[ 05 06 07 08 09 0A 0B 0C ] ( address, in hex )
[ .. .. 00 00 00 00 01 .. ] ( value, in hex )
And at last I just print it as if it were an 8 byte integer:
cout << ( *( int64_t* ) &charPointer ) << endl;
So, can anybody explain why it isn’t the value of the pointer that is added but the value of what’s being pointed to?
These conversions exist, but they don’t do what you think they do. Converting a pointer to an integer is just treating it as an integer; it’s not doing any actual “math”. For example,
char * s = "abcd"; int i = (int) s;will not give the same result every time, becausesandiare both just the memory address that the string starts at. Neither has anything to do with the actual contents of the string.Similarly,
char* + intis just taking an offset. To writechar * s = "abcd"; char * t = s + 2;is just another way to writechar * s = "abcd"; char * t = &(s[2]);; that is,sis the memory location of the'a', andtis the memory location of the'c'(s, offset by twochar-widths, that is, two bytes). No actual math has taken place, except in the sense that “pointer arithmetic” requires math to compute byte offsets and find memory locations.char * + char *doesn’t make sense: what would it mean to “add” two memory locations together?Edit: Here is the code you added to your question:
Let me expand it a bit, so it’s a bit clearer what’s going on:
Does that make sense?