Convert a binary string into UInt16

in deutsch •  last year 

Konvertiere ein Binärstring und wandel die Binärzahl in einen 16-bit unsigned Integer um.

public class BinaryConverter {

    public UShort binaryStringToUShort(final String binaryString){
        if(binaryString.length() != 16){
            return new UShort(0);
        }
        int value = 0;
        int m = 0;
        for(int n = binaryString.length() - 1; n >= 0; n--){
            if(binaryString.charAt(n) == '1'){
                value += Math.pow(2,m);
            }
            m++;
        }
        return new UShort(value);
    }

    public String UShortToBinaryString(final UShort value){
        StringBuilder sb = new StringBuilder();
        int temp = value.getValue();
        int m = 15;
        for(int n = 0; n <= 15; n++){
            if(temp / (int) Math.pow(2,m) == 1){
                sb.append('1');
                temp -= (int) Math.pow(2,m);
            } else {
                sb.append('0');
            }
            m--;
        }
        return sb.toString();
    }

    public static void main(String[] args){
        BinaryConverter bc = new BinaryConverter();
        UShort stringValue = bc.binaryStringToUShort("0010000000011100");
        System.out.println(stringValue.getValue());
        String origin = bc.UShortToBinaryString(stringValue);
        System.out.println(origin);
    }
}




Posted from https://blurtlatam.intinte.org

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE BLURT!
Sort Order:  

This post has been manually upvoted by @epistem


You are invited to use the tag #epistem when posting within the niche of the community. Also, follow us on @epistem and on our Discord community to keep abreast with the activities of the community.