Convert IP addresses from decimal to IPv4 and format output using vectoring
Show older comments
Hello,
I want to convert a vector of IP addresses in decimal format to the IPv4 format.
So far I have implemented this using a for loop and the output is a cell array of chars.
function result = dec2IP(decimalIP)
% Derive the octets
dec = double(decimalIP);
byte1=floor(dec/power(256,3));
mod1=mod(dec, power(256,3));
byte2=floor(mod1/power(256,2));
mod2=mod(mod1, power(256,2));
byte3=floor(mod2/power(256,1));
mod3=mod(mod2, power(256,1));
byte4=floor(mod3/power(256,0));
% Convert to char array
for i=1:length(decimalIP)
result(i) = {[int2str(byte1(i)), '.', int2str(byte2(i)), '.', int2str(byte3(i)), '.', int2str(byte4(i))]};
end
end
Is there a way to implement this using vectoring instead of a loop?
Thanks, George
Accepted Answer
More Answers (1)
J-G van der Toorn
on 3 Dec 2015
I was thinking about this inline function:
ipstr = @(ip)sprintf('%d.%d.%d.%d',arrayfun(@(n)floor(mod(ip,2^(n*8))/2^((n-1)*8)),4:-1:1));
But with bitshift, it's also possible:
ipstr=@(ip)sprintf('%d.%d.%d.%d',arrayfun(@(n)bitand(bitshift(ip,-32+n*8), 255),1:4));
and even shorter. There might be an even shorter notation on Cody, or it will be there soon.
Categories
Find more on Data Type Conversion in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!