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?

Nicholas
  • 783
  • 2
  • 7
  • 25
  • Why do you want to represent the bits with a string? – Erik Dietrich Mar 22 '12 at 14:53
  • Possible duplicate: [Calculate broadcast address from ip and subnet mask](http://stackoverflow.com/questions/777617/calculate-broadcast-address-from-ip-and-subnet-mask) – Devendra D. Chavan Mar 22 '12 at 14:56
  • I can't use bytes as it's homework, if that is what you would suggest me using :) – Nicholas Mar 22 '12 at 14:56
  • @DevendraD.Chavan i did see that post, but, they are using C and uint's so i can't use it for strings – Nicholas Mar 22 '12 at 14:58
  • 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. – Erik Dietrich Mar 22 '12 at 15:00
  • 1
    @balls, this should help in converting bit string to bytes [[How to convert a string of bits to byte array](http://stackoverflow.com/questions/2989695/how-to-convert-a-string-of-bits-to-byte-array)] and then to integer [[BitConverter.ToUInt32 Method](http://msdn.microsoft.com/en-us/library/system.bitconverter.touint32.aspx)]. – Devendra D. Chavan Mar 22 '12 at 15:04

1 Answers1

1

This should do the trick:

string network = "11000010101000000000010000000";
network = network.Substring(0, network.Length - 8) + "11111111";
Brian
  • 1,803
  • 1
  • 16
  • 22
  • This doesn't work as Substring() takes (network.Length-8) as starting Index..it should be network.Substring(0,network.Length-8) – Flowerking Mar 22 '12 at 15:10
  • I'm sorry, I totally forgot about the starting index. Thank you for clearing that up Flowerking! – Brian Mar 22 '12 at 15:34