TE
TechEcho
Home24h TopNewestBestAskShowJobs
GitHubTwitter
Home

TechEcho

A tech news platform built with Next.js, providing global tech news and discussions.

GitHubTwitter

Home

HomeNewestBestAskShowJobs

Resources

HackerNews APIOriginal HackerNewsNext.js

© 2025 TechEcho. All rights reserved.

What is a safest way to set all bits of a variable to true in C?

33 pointsby niyazpkover 14 years ago

6 comments

edanmover 14 years ago
Personally I'd use: unsigned int a = 0xFFFF, not unsigned int a = -1.<p>This is a classic case of a readability issue. 0xFFFF is, in my mind, much clearer on your intention than -1. The only problem is that you're assuming a specific int size, but really, if you're working with bits, chances are good that you're working on a platform where you <i>know</i> the architecture size (at least on embedded platforms).
评论 #1779185 未加载
评论 #1782798 未加载
评论 #1780492 未加载
senkiover 14 years ago
The "limits.h" (ISO C99 Standard) defines UINT_MAX as the maximum value for a variable of type unsigned int which is 4294967295 (0xffffffff).
评论 #1779305 未加载
评论 #1780483 未加载
pointsover 14 years ago
How many 'ones complement' machines exist?
评论 #1779216 未加载
Someoneover 14 years ago
In C99, integer types can have padding bits that may not be writable, and writing all ones can be 'a trap representation' (except for the cas of unsigned char). So, I would guess that the portable way to do this requires taking the address of the variable, casting to (char unsigned *), and writing sizeof(var) all-ones unsigned char patterns (however that has to be done). I am not a C expert, though, so feel free to correct me.
loup-vaillantover 14 years ago
But but but, this doesn't answer the question!? It explicitly acknowledges that -1 will not always set all bits to one, yet it recommends it!<p>That makes me very surprised by (1) the number of up-votes, and (2) the green "check" mark of approval.
评论 #1779857 未加载
jrockwayover 14 years ago
The next question: Why?<p>(To clarify: I mean, "why do you care what the bits are set to".)
评论 #1779349 未加载
评论 #1779083 未加载
评论 #1779203 未加载
评论 #1779095 未加载