1

I want to calculate the broadcast of an IP address, I calculated the network address (by ANDing) and now i need the broadcast address, the method I'm using is just to turn all the hostbits on the network address to 1, to get the last possible IP address.

Now the problem is how to do it :-)

Anyway, the idea is this:
           netbits                    hostbits  
Network:   11000000 10101000 00000001 00000000 <- 192.168.1.0  
Subnet:    11111111 11111111 11111111 00000000 <- 255.255.255.0  
Broadcast: 11000000 10101000 00000001 11111111 <- 192.168.1.255

If they are all in a string, how do I convert the last portion to 1's (replace the 0's) in a string?

I know how many 0s there are, and i have the network in a string (as well as in an array just in case)

int hostbits = 8;
string network ="11000010101000000000010000000";

 string[] arraynetwork = new string[4]
 arraynetwork[0] = "11000000";
....

Any ideas?

6
  • Why do you want to represent the bits with a string? Commented Mar 22, 2012 at 14:53
  • Possible duplicate: Calculate broadcast address from ip and subnet mask Commented Mar 22, 2012 at 14:56
  • I can't use bytes as it's homework, if that is what you would suggest me using :) Commented Mar 22, 2012 at 14:56
  • 2
    @balls I'd use ints, since that's ultimately what they are. That also gets you native bit arithmetic operations. If it weren't specifically assigned as homework, I think the thing would be to convert the strings you get from users into ints and then perform your calculations. Commented Mar 22, 2012 at 15:00
  • 1
    @balls, this should help in converting bit string to bytes [How to convert a string of bits to byte array] and then to integer [BitConverter.ToUInt32 Method]. Commented Mar 22, 2012 at 15:04

1 Answer 1

1

This should do the trick:

string network = "11000010101000000000010000000";
network = network.Substring(0, network.Length - 8) + "11111111";
Sign up to request clarification or add additional context in comments.

2 Comments

This doesn't work as Substring() takes (network.Length-8) as starting Index..it should be network.Substring(0,network.Length-8)
I'm sorry, I totally forgot about the starting index. Thank you for clearing that up Flowerking!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.