Convert IP addresses from decimal to IPv4 and format output using vectoring
Afficher commentaires plus anciens
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
Réponse acceptée
Plus de réponses (1)
J-G van der Toorn
le 3 Déc 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.
Catégories
En savoir plus sur Data Type Conversion dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!