5 ms·
Your hunch would be wrong. #include <stdio.h> int main (int argc, char *argv[]) { unsigned int ip = 3232235777u; printf ("%d.%d.%
by audidude 17y ago
Your hunch would be wrong.
#include <stdio.h>
int
main (int argc,
char *argv[])
{
unsigned int ip = 3232235777u;
printf ("%d.%d.%d.%d\n",
(ip & 0xFF000000) >> 24,
(ip & 0x00FF0000) >> 16,
(ip & 0x0000FF00) >> 8,
(ip & 0x000000FF));
return 0;
}
- tptacek 17y agoWhat does this code demonstrate, other than that you're unconcerned with endianness? Converting "192.168.1.1" to an integer in Ruby involved creating multiple array, string, and integer objects, not to mention several multiply-indirected method calls.
- audidude 17y agoip addresses are always stored in network-byte-order
- tptacek 17y agoYour ALU doesn't care what the RFC says. What's the point of storing addresses in binary if you can't do math on them? There is no point, is the point.
- haberman 17y agoThis code is not endian-dependent. You can only observe endianness when you address the same memory as two different types: int x = 5; char *chp = (char*)&x; printf("This value is endian-dependent: %hhd\n", *chp);
- tptacek 17y agoThe code isn't endian-dependent because it doesn't do anything. The only thing you can do with "3232235777" on a little-endian machine is compare it to another number to see if it's also "3232235777". If you're going to store IP addresses as 32 bit integers, or work with them that way in your C code, 192.168.1.1 should be "16885952", so you can do > and <. But your point is well taken, and audiguy, I'm sorry for being such an asshole in my comment.