Convert IP addresses from decimal to IPv4 and format output using vectoring
12 views (last 30 days)
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
0 Comments
Accepted Answer
Ashish Gudla
on 4 Aug 2014
You can probably convert the IP address from decimal to IPv4 format using vectorization however its not very intuitive. I used a different logic to convert.
Each value in IPv4 format can be obtained by applying bit operations on the decimal number as follows.
Right shift the decimal value 24 bits and apply “bitand” operator to the resulting number and 255. Similarly for the other values, right shift by 16 ,8 and 0 bits.
1st value :
bitand(bitshift(IPVector,-24), 255)
2nd value :
bitand(bitshift(IPVector,-16), 255)
3rd value :
bitand(bitshift(IPVector,-8), 255)
4th value :
bitand(bitshift(IPVector,0), 255)
Now you can simply concatenate all the 4 values with a “.” In between them to form a IPv4 format address using the following command:
strcat(
num2str(bitand(bitshift(IPVector,-24), 255)) ,'.',
num2str(bitand(bitshift(IPVector,-16), 255)) ,'.',
num2str(bitand(bitshift(IPVector,-8), 255)) ,'.',
num2str(bitand(bitshift(IPVector,0), 255))
)
Example:
>> IPVector = [3232235778 ; 3232235780 ; 3232235890]
IPVector =
1.0e+09 *
3.2322
3.2322
3.2322
>> IPVector_new = strcat(num2str(bitand(bitshift(IPVector,-24), 255)),'.',num2str(bitand(bitshift(IPVector,-16), 255)) ,'.',num2str(bitand(bitshift(IPVector,-8), 255)) ,'.',num2str(bitand(bitshift(IPVector,0), 255)) )
IPVector_new =
192.168.1. 2
192.168.1. 4
192.168.1.114
>> IPVector_new = strrep(cellstr(IPVector_new),' ','')
IPVector_new =
'192.168.1.2'
'192.168.1.4'
'192.168.1.114'
0 Comments
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.
0 Comments
See Also
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!