I'm rusty with arrays. I have an array: int bits [8] = { 128, 64, 32, 16, 8, 4, 2, 1 }
When I try to use a for loop to output each element, it does output all of the elements but then about 20 times outputs odd negative and large positive numbers.
Why?
1 2 3
int bits [8] = { 128, 64, 32, 16, 8, 4, 2, 1 };
for (int i = 0; i < sizeof(bits); i++)
cout << bits[i] << endl;
I'm pretty sure it has something to do with the sizeof function. How can I iterate the for loop, without using i < 8 - I want it to measure the array size of bits and check i against that.
but perhaps slightly more general would be: int len=sizeof(bits)/sizeof(bits[0]);
The latter will continue to work even if the array bits is a different datatype.
Good - The following code outputs 0000000.0000000.0000000.0000000 and not the correct thing I'm after. I'm using the below code to check if bits[i] - octetsIP[j] is negative (which in this case would mean vector octetsBits should push_back 0), but if it does subtract, and is not negative it should be a 1.
What am I doing wrong?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
int getNHBits(vector<int> &octetsIP, vector<int> &octetsMask){
// Determine Binary /--
int bits[8] = { 128, 64, 32, 16, 8, 4, 2, 1 };
vector<int> octetsBits;
for(int j=0; j < octetsIP.size(); j++){ // loop each of the 4 ip octets
for(int i=0; i < 8; i++){ // while looping .. loop each 8 elements of bits array
if (bits[i] - octetsIP[j] < 0) // test if bits - octetsIP is a negative number ...
octetsBits.push_back(0); // ... if negative, push a 0 to octetsBits
else
octetsBits.push_back(1); // ... else push a 1 to octetsBits
cout << octetsBits[i]; // output octetsBits elements, as binary 0 or 1
} // STOP looping 8 bits array
cout << "."; // make binary conversion into dot notation
} // STOP looping 4 ip octets
return 0;
}
Sorry - I don't think i've accounted for the new assignment of octetsIP[j]'s new total after successful subtraction of bits, for each iteration.... I'm just having trouble figuring out with octetsBits is always 0 now. Maybe a side effect of the aforementioned
EDIT* Figured it out, I just have to account for the new totals.. i think
I got a bit lost in all that code. I wasn't really sure of the actual goal. Were you intending to convert each octet into a binary representation, or something different?