log2()

log2(x)
Returns: numeric · Updated March 13, 2026 · Base Functions
math log log2 logarithm base

The log2() function computes the logarithm of a number in base 2. This is particularly useful in computer science and information theory.

Syntax

log2(x)

Parameters

ParameterTypeDefaultDescription
xnumericA numeric vector or scalar

Examples

Basic usage

# Log base 2 of 2 is 1
log2(2)
# [1] 1

# Log base 2 of 8 is 3
log2(8)
# [1] 3

# Log base 2 of 1024 is 10
log2(1024)
# [1] 10

# Working with vectors
log2(c(1, 2, 4, 8, 16))
# [1] 0 1 2 3 4

Common Patterns

Information theory

# Bits needed to represent n values
n <- 100
ceiling(log2(n))
# [1] 7

# Information entropy
probs <- c(0.5, 0.25, 0.125, 0.125)
-sum(probs * log2(probs))
# [1] 1.75

Binary representations

# Find the bit position
x <- 16
log2(x)
# [1] 4

# Check if number is power of 2
is_power_of_2 <- function(n) n > 0 && (n & (n - 1)) == 0
is_power_of_2(8)
# [1] TRUE

is_power_of_2(10)
# [1] FALSE

Algorithm complexity

# Binary search complexity: O(log2(n))
n <- 1000
log2(n)
# [1] 9.965784

See Also