-1

I encountered this line of code:

    memset(tmp, 0, (-len) & 0x7F);

Where len is a uint8_t pointer variable.

What's is the "-" doing to len before the bitwise operation? What would be the result?

Given it is an unsigned integer, I don't think it'd make sense to add a sign this way (if it is at all possible in C), even less with it being a pointer.

  • 3
    Please provide the full context of the code. That is, give a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) – kaylum Aug 13 '21 at 21:51
  • 3
    The `uint8_t` type is not a pointer type. If your `len` is actually a `uint8_t*` pointer, then your code won't compile. – Adrian Mole Aug 13 '21 at 21:52
  • @Santiago Marruffo len is not a pointer. You may not apply the unary operator - to pointers. – Vlad from Moscow Aug 13 '21 at 21:59
  • You need to provide more context and correct the error about `len` being any kind of pointer, but, for an unsigned integer type or a two’s complement type, `-len & 0x7F` evaluates to the smallest number of bytes `x` such that `len+x` is a multiple of 128. E.g., for `len` = 0, 128, or 256, `-len & 0x7F` is zero. For `len` = 1, 129, or 257, it is 127. For `len` = 2, it is 126. For `len` = 127, it is 1. This calculation is sometimes used to calculate how much padding is needed to fill out space up to a multiple of a number. – Eric Postpischil Aug 13 '21 at 22:52
  • `uint8_t *len = ...; memset(tmp, 0, (-len) & 0x7F);` --> "error: wrong type argument to unary minus" – chux - Reinstate Monica Aug 13 '21 at 23:02

1 Answers1

3

len cannot be a pointer to a variable, because the unary minus operator cannot accept a pointer as an operand. The code would not compile. Considering the function prototype of memset, it is more likely that len is of the type uint8_t here. The behavior of applying the unary minus operator on unsigned types is described here.

Yun
  • 3,056
  • 6
  • 9
  • 28