본문 바로가기
카테고리 없음

num to ip

by pishio 2024. 9. 24.

// 마지막 3개의 옥텟을 정수로 변환한 값을 다시 IP로 변환하는 함수 (비트 연산 없이, 최적화)
function intToLast3Octets(ipInt) {
    const divisor = 256;  // 상수로 반복되는 256 값을 저장
    const octet1 = Math.floor(ipInt / (divisor * divisor)); // 첫 번째 옥텟
    const remainder = ipInt % (divisor * divisor); // 남은 값을 저장해 중복 계산 방지
    const octet2 = Math.floor(remainder / divisor); // 두 번째 옥텟
    const octet3 = remainder % divisor; // 세 번째 옥텟

    return `${octet1}.${octet2}.${octet3}`;
}

// 예시 정수값 (예: 226.155.9을 정수로 변환한 값)
const ipInt = (226 * 256 * 256) + (155 * 256) + 9;

// 변환된 IP를 출력
console.log(intToLast3Octets(ipInt)); // 출력: "226.155.9"





// 마지막 3개의 옥텟을 정수로 변환한 값을 다시 IP로 변환하는 함수 (비트 연산 없이)
function intToLast3Octets(ipInt) {
    // 각 옥텟을 산술 연산으로 분리
    const octet1 = Math.floor(ipInt / (256 * 256)); // 첫 번째 옥텟
    const octet2 = Math.floor((ipInt % (256 * 256)) / 256); // 두 번째 옥텟
    const octet3 = ipInt % 256; // 세 번째 옥텟

    // 옥텟을 다시 '.'으로 연결하여 IP 형식으로 변환
    return `${octet1}.${octet2}.${octet3}`;
}

// 예시 정수값 (예: 226.155.9을 정수로 변환한 값)
const ipInt = (226 * 256 * 256) + (155 * 256) + 9;

// 변환된 IP를 출력
console.log(intToLast3Octets(ipInt)); // 출력: "226.155.9"

댓글