Live data from Hacker News

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

stackoverflow.com

1–10 of 30 posts

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

#5
post #4
post #2

The next question: Why? (To clarify: I mean, "why do you care what the bits are set to".)

Because of two's complement and the way implicit conversions work.

It is independent of the representation of negative numbers on the machine, because of the conversion rules.

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

#7
Personally I'd use: unsigned int a = 0xFFFF, not unsigned int a = -1.

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 know the architecture size (at least on embedded platforms).

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

#8
post #7

Personally I'd use: unsigned int a = 0xFFFF, not unsigned int a = -1. 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 know the architecture size (at least on embedded platforms).

The problem is that you can't be sure how many bytes and int is on any given platform. So your way is more readable, but not portable.

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

#9
post #8
post #7

Personally I'd use: unsigned int a = 0xFFFF, not unsigned int a = -1. 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 know the architecture size (at least on embedded platforms).

The problem is that you can't be sure how many bytes and int is on any given platform. So your way is more readable, but not portable.

[deleted]

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

#10
post #8
post #7

Personally I'd use: unsigned int a = 0xFFFF, not unsigned int a = -1. 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 know the architecture size (at least on embedded platforms).

The problem is that you can't be sure how many bytes and int is on any given platform. So your way is more readable, but not portable.

Crap. This is why you don't respond without fully reading a comment. Where is my delete option? :-)
Post reply on HN