Nicholas
Nicholas

Reputation: 793

C# Replace last letters with another in a String

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?

Upvotes: 1

Views: 298

Answers (1)

Brian
Brian

Reputation: 1823

This should do the trick:

string network = "11000010101000000000010000000";
network = network.Substring(0, network.Length - 8) + "11111111";

Upvotes: 1

Related Questions