Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confused about the use of ptrdiff_t in C++

Tags:

java

c++

porting

I need to translate this line of code in Java and I am not sure what to do about ptrdiff_t. Not sure what it does here. By the way, mask_block is of type size_t.

size_t lowest_bit = mask_block & (-(ptrdiff_t)mask_block);

Thanks

like image 719
user1796942 Avatar asked Dec 08 '22 18:12

user1796942


2 Answers

Beware! This is bit magic!

( x & ~(x-1) ) returns the lowest set bit in an expression. The author of the original code decided to use ( x & (-x) ) which is effectively the same due to the two's comlement representation of integers. But (the original author thought that) to get -x you need to use signed types and, as pointed out earlier, ptrdiff_t is signed, size_t is unsigned.

As Java does not have unsigned types, mask_block will be int and mask_block & (-mask_block) will work without any issue.

Note that due to the interoperability between signed and unsigned types, the cast is superfluous in C++ as well.

like image 192
Csq Avatar answered Dec 11 '22 07:12

Csq


ptrdiff_t is the type that should be used for the (integer) difference between two pointers. That is, the result of subtracting one pointer from another. It is a signed integer, and should be large enough to stroe the size of largest possible array (so in Java, that would simply be an int, I'd guess)

like image 39
jalf Avatar answered Dec 11 '22 09:12

jalf