0

I 'm reading the protocol specification that it explain byte 0 : 0b0000001x if line Available. So, I must create packet according to this doc, but I don't know how to assign 0b0000001x to the variable in C. I have :

unsigned char * payload;
payload[0] = 0b0000001x;

But I get the following error:

error: unable to find numeric literal operator ‘operator"" x0’

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
PersianGulf
  • 2,845
  • 6
  • 47
  • 67
  • 6
    `0b0000001x` is not a valid numeric expression in C. In your specification it most likely means "this is a binary number, i.e. a sequence of bits", and `x` is the bit you should set or clear according to the current state of the line. If I'm reading this correctly and the endianness is correct, the resulting byte value should be `(2 + (is_line_available ? 1 : 0))`. (Also, you are not allocating any space for `payload` and so you'll write into random memory.) – DCoder Aug 11 '12 at 14:29
  • 1
    @DCoder: +1 post that as an answer – Aziz Aug 11 '12 at 14:30

2 Answers2

4

Based on your specification, 0b0000001x most likely means "this is a binary number, i.e. a sequence of bits", and x is the bit you should set or clear according to the current state of the line. Builtin binary literals are only supported in C++14 or above, in C++11 they can be implemented as user-defined literals, in C and older versions of C++ you need to compute the value manually (or you can use a compiler that implements this as a non-standard extension, both gcc and clang do so).

If I'm reading this correctly and the endianness is correct, the resulting byte value should be:

payload[0] = 2 + (is_line_available ? 1 : 0);

Also, you are not allocating any space for payload and so you'll write into random memory. You need to allocate some memory:

Static allocation, works in both C and C++:

unsigned char payload[24]; // or whatever your message's length is

C-style dynamic allocation (make sure to free it after you're done):

unsigned char *payload = malloc(24);
...; 
free(payload);

C++ recommended approach:

#include <vector>
std::vector<unsigned char> payload;
payload.reserve(24);
...;
Community
  • 1
  • 1
DCoder
  • 12,962
  • 4
  • 40
  • 62
  • I don't remember if this is only in GCC, or if it's a new thing in the standard, but https://gcc.gnu.org/onlinedocs/gcc/Binary-constants.html. (that link says `i = 0b101010;`.) – lmat - Reinstate Monica Jun 20 '16 at 13:37
  • @LimitedAtonement: It might have been a GCC extension earlier. It's also [part of C++14](https://en.wikipedia.org/wiki/C%2B%2B14#Binary_literals) nowadays, I'll update this answer shortly to reflect that. – DCoder Jun 20 '16 at 15:06
1

It looks like C doesn't support binary literals. Try using hex instead.

payload[0] = 0x01;
Community
  • 1
  • 1
Antimony
  • 37,781
  • 10
  • 100
  • 107