function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Suman GiriSuman Giri 

How to convert binary string into integer ??

Hi,

 

There is a requirement for us where we receive binary string which needs to be converted into integer. We could acheive this in java with the below code:

 

 String binaryString="00000101";
 System.out.println(Integer.parseInt(binaryString, 2));

 

Output what we get is '5'.

Could we acheive this using Apex ?

Any pointers would be of great help.

Thanks in advance.

 

Regards,

Suman.H

Best Answer chosen by Admin (Salesforce Developers) 
SamuelDeRyckeSamuelDeRycke
public with sharing class GeneralUtils {
public static integer stringByteToInteger(string b){
			// '76543210' -> 128-64-32-16-8-4-2-1
			try{
				double result = 0.0;
				integer i = 7;
				integer x = 0;
				while(i>=0){
					result += math.pow(double.valueof(2.0),double.valueof(i)) * integer.valueof(b.substring(x,x+1));
					x++;
					i--;
				}
				return result.intvalue();
			}catch(Exception x){
				throw new CustomErrorException('Invalid Byte String: '+ b);
			}
	}
public class CustomErrorException extends Exception {} }

 

 

All Answers

MandyKoolMandyKool

Hi,

 

In Apex, Integers do not have any method to directly convert binary to integer.

You will have to build your own logic to achieve this.

 

 

SamuelDeRyckeSamuelDeRycke
public with sharing class GeneralUtils {
public static integer stringByteToInteger(string b){
			// '76543210' -> 128-64-32-16-8-4-2-1
			try{
				double result = 0.0;
				integer i = 7;
				integer x = 0;
				while(i>=0){
					result += math.pow(double.valueof(2.0),double.valueof(i)) * integer.valueof(b.substring(x,x+1));
					x++;
					i--;
				}
				return result.intvalue();
			}catch(Exception x){
				throw new CustomErrorException('Invalid Byte String: '+ b);
			}
	}
public class CustomErrorException extends Exception {} }

 

 

This was selected as the best answer