On Thu, Mar 22, 2018 at 12:31 PM, Alexei Starovoitov <ast@xxxxxx> wrote: > > yeah. C doesn't allow casting of 'struct s { u64 var };' into u64 > without massive hacks and aliasing warnings by compiler. Without massive hacks? Yeah, no. But without warnings? You can do it. #define UINTTYPE(size) \ __typeof__(__builtin_choose_expr(size==1, (u8)1, \ __builtin_choose_expr(size==2, (u16)2, \ __builtin_choose_expr(size==4, (u32)3, \ __builtin_choose_expr(size==8, (u64)4, \ (void)5))))) #define CAST_TO_U64(x) ({ \ typeof(x) __src = (x); \ UINTTYPE(sizeof(x)) __dst; \ memcpy(&__dst, &__src, sizeof(__dst)); \ (u64)__dst; }) Yeah, I'm not proud of the above, but gcc actually seems to do the right thing for it. Doing struct d { unsigned char a,b; }; it generates movzwl %di, %eax for the CAST_TO_U64() (the above *looks* like it only casts to 32-bit, but it is actually a full cast to 64 bits because movzwl will also clear the top bits of the register). No warnings. But is ot "massively hacky"? You be the judge. Probably. Going the other way is trivial, you just use that same UINTTYPE() again and just the memcpy in reverse. NOTE! The above obviously only works for things that are actually proper nice easy sizes. If you want to encode a 6-byte thing in a u64, the sanest thing is likely to use a union, and just accept crap in some bytes of the u64 (and just expect it to be undone by the reversal operation). Honestly, I'd suggest against it, because of just horrible code generation and/or data leakage Linus -- To unsubscribe from this list: send the line "unsubscribe linux-api" in the body of a message to majordomo@xxxxxxxxxxxxxxx More majordomo info at http://vger.kernel.org/majordomo-info.html