Convert IP addresses from decimal to IPv4 and format output using vectoring
显示 更早的评论
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
采纳的回答
更多回答(1 个)
J-G van der Toorn
2015-12-3
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.
类别
在 帮助中心 和 File Exchange 中查找有关 Data Type Conversion 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!