-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNumberSystemConversion.r
More file actions
65 lines (56 loc) · 2.09 KB
/
Copy pathNumberSystemConversion.r
File metadata and controls
65 lines (56 loc) · 2.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
decimal_to_binary <- function(decimal) {
return(as.character(intToBits(decimal)[intToBits(decimal) > 0]))
}
binary_to_decimal <- function(binary) {
return(sum(as.numeric(rev(strsplit(binary, NULL)[[1]])) * 2^(0:(nchar(binary)-1))))
}
decimal_to_octal <- function(decimal) {
return(as.character(as.octal(decimal)))
}
octal_to_decimal <- function(octal) {
return(as.integer(strtoi(octal, base = 8)))
}
hexadecimal_to_binary <- function(hexadecimal) {
return(as.character(intToBits(strtoi(hexadecimal, base = 16))))
}
binary_to_hexadecimal <- function(binary) {
return(as.character(as.hexmode(strtoi(binary, base = 2))))
}
main <- function() {
repeat {
cat("\nMenu:\n")
cat("1. Decimal to Binary\n")
cat("2. Binary to Decimal\n")
cat("3. Decimal to Octal\n")
cat("4. Octal to Decimal\n")
cat("5. Hexadecimal to Binary\n")
cat("6. Binary to Hexadecimal\n")
cat("7. Exit\n")
choice <- as.integer(readline(prompt = "Enter your choice: "))
if (choice == 1) {
decimal <- as.integer(readline(prompt = "Enter a decimal number: "))
cat("Binary:", paste0(decimal_to_binary(decimal), collapse = ""), "\n")
} else if (choice == 2) {
binary <- readline(prompt = "Enter a binary number: ")
cat("Decimal:", binary_to_decimal(binary), "\n")
} else if (choice == 3) {
decimal <- as.integer(readline(prompt = "Enter a decimal number: "))
cat("Octal:", decimal_to_octal(decimal), "\n")
} else if (choice == 4) {
octal <- readline(prompt = "Enter an octal number: ")
cat("Decimal:", octal_to_decimal(octal), "\n")
} else if (choice == 5) {
hexadecimal <- readline(prompt = "Enter a hexadecimal number: ")
cat("Binary:", paste0(hexadecimal_to_binary(hexadecimal), collapse = ""), "\n")
} else if (choice == 6) {
binary <- readline(prompt = "Enter a binary number: ")
cat("Hexadecimal:", binary_to_hexadecimal(binary), "\n")
} else if (choice == 7) {
cat("Exiting program. Goodbye!\n")
break
} else {
cat("Invalid choice. Please enter a valid option (1-7).\n")
}
}
}
main()