Write a function to decode an octal string to a number in an array of bytes

0

Write a function to decode an octal string to a number in an array of bytes. For example,
“31646541” should produce [103, 77, 97].

Optional
To increase the challenge, consider the following:
1. Write the corresponding encode function
2. Add hexadecimal support
3. Add base32 or base64 support
4. Use your functions to express a sha1 digest in 24 chars
5. Write a property based test
6. Does it work for octal:
“116311474231113516702134342400414143206126403671660545535070012425145143
3665154621070427104557201067171276700627170465777043334607301704736021762
6325467150763006577133541526554667660414027165423126701315057614760526500
0452421616177052165224543311447543654741617367042213645643631333465753306
2163564254163664432653550166600433332675642447003252221104064117622317044
717471253″

Answered question
0
Javakid (anonymous) 0 Comments

From the problem statement it’s clear that the octal string is first converted into binary string and then the binary string is converted into decimal value bytes (8 bits each). If the binary string is not in multiples of 8, zeroes are padded in the beginning of it to make it evenly divisible by 8.

 

Java code to achieve the same:-

/* Java Program Example - Convert Octal to Binary String */
  import java.nio.*;
import java.util.*;
 class JavaProgram {
    public static void main(String args[]) {
        int octnum, rem, quot, i = 1, j;
        int binnum[] = new int[100];
        Scanner scan = new Scanner(System.in);
         System.out.print("Enter Octal Number : ");
        octnum = scan.nextInt();
         quot = octnum;
         while (quot != 0) {
            binnum[i++] = quot % 2;
            quot = quot / 2;
        }
         System.out.print("Equivalent Binary Value of " + octnum + " is :\n");
        for (j = i - 1; j > 0; j--) {
            System.out.print(binnum[j]);
        }
         String strArray[] = Arrays.stream(binnum)
            .mapToObj(String::valueOf)
            .toArray(String[]::new);
         System.out.println(strArray);
         System.out.println(binaryToString(strArray.toString()));
     }
     public static String binaryToString(String binary) {
        String output = "";
        for (int i = 0; i < binary.length(); i += 8) {
            String next = binary.substring(i, i + 8);
            int code = Integer.parseInt(next, 2);
            output += ((char) code);
        }
        return output;
    }
}

Changed status to publish
You are viewing 1 out of 3 answers, click here to view all answers.
Write your answer.

Categories