3

I am working with the xc8 compiler and want to tell him that my literal is only 8 bit wide.

123 :no suffix, default int (16 bit in xc8)

123U :unsigned int also 16 bit wide

Any idea for a clean solution to describe a 8 bit literal?

Mike
  • 4,041
  • 6
  • 20
  • 37

3 Answers3

1

Any idea for a clean solution to describe a 8 bit literal?

C only has 2 literals: string literals and compound literals (C99). C identifies 123 and 123u as integer constants, not literals.

To form a C 8 bit literal: make a compound literal

#define OneTwoThree ((uint8_t) { 123 })
printf("%zu %x\n", sizeof(OneTwoThree), OneTwoThree);

// expected output
1 123

IDK if xc8 supports compound literals.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
0

There are no 8 bit literals in C. The closest thing you can get is UINT8_C(123) from stdint.h, which gives you the literal most suitable for a variable of type uint_least8_t. Very likely it will expand to 123U.

As for how to solve this practically, you show the constant into a define, which you should be doing anyway:

#define NUMBER_8BIT ( (uint8_t)123 )
Lundin
  • 195,001
  • 40
  • 254
  • 396
  • 1
    A commonly used trick for such constants is to add a `+` such that it also may appear in preprocessor conditionals, something like `((uint8_t)+123)`. – Jens Gustedt May 31 '18 at 07:54
  • I disagree that there are no 8 bit literals in C. Counter example: [`(uint8_t) { 123 }`](https://stackoverflow.com/a/50626361/2410359) – chux - Reinstate Monica May 31 '18 at 15:04
  • @chux Well formally they aren't called literals but integer constants. Literal was the term used by the OP so I kept it. – Lundin Jun 01 '18 at 06:31
0

Type convert to (unsigned char)

user50619
  • 325
  • 5
  • 14