WodkaRHR
WodkaRHR

Reputation: 175

C casting unsigned char to unsigned char : 4

I currently have an issue concerning a warning. I have a method return a u8 value, where u8 was defined as unsigned char.

u8 foo (...)

And inside a structure I have a member x that only needs 4 bits.

struct {
     u8 x : 4;
     u8 y : 4;
} s;

Now I want to assign the return value of foo to x. However my compiler throws a warning about possible loss by conversion from unsigned char to unsigned char : 4. Yet a cast like this isn't recognized.

struct_inst.x = (u8 : 4)foo(..);

What is the proper syntax for this?

Upvotes: 2

Views: 1105

Answers (1)

Jens Gustedt
Jens Gustedt

Reputation: 78903

Bitfield types as you have them with your :4 aren't proper types in C's type system, so you cannot use them in casts.

Your compiler warning is a bit execessive, conversion from one unsigned type to another is well defined. The sense of the warning is correct, nevertheless, converting an 8 bit type to a 4 bit field may loose information. Maybe you could silence your compiler by anding your return value with 0xF so the compiler sees that you are willingly throwing the higher bits away.

BTW:

  • There is a type uint8_t in <stdint.h> that has the properties that you want.

  • Using types that are narrower than int is not a good idea in most cases, because they always promote to int in arithmetic, anyhow. Only use them if the few bytes that you gain are really worth it. They aren't if you have Gigabytes of memory in your system, e.g.

  • Bitfields are even less usefull than narrow integer types.

Upvotes: 4

Related Questions