Tuesday, 19 July 2022

How to get the string size in bits?

'string.getBytes(stringEncoding).length * 8' return the string length in bits.

 

StringLengthInBits.java

package com.sample.app;

import java.nio.charset.StandardCharsets;

public class StringLengthInBits {

	public static void main(String[] args) {
		String str1 = "Hello World";

		System.out.println("length in " + StandardCharsets.ISO_8859_1 + " is "
				+ str1.getBytes(StandardCharsets.ISO_8859_1).length * 8);

		System.out.println("length in " + StandardCharsets.US_ASCII + " is "
				+ str1.getBytes(StandardCharsets.US_ASCII).length * 8);

		System.out.println("length in " + StandardCharsets.UTF_16 + " is " + str1.getBytes(StandardCharsets.UTF_16).length * 8);

		System.out.println("length in " + StandardCharsets.UTF_16BE + " is "
				+ str1.getBytes(StandardCharsets.UTF_16BE).length * 8);

		System.out.println("length in " + StandardCharsets.UTF_16LE + " is "
				+ str1.getBytes(StandardCharsets.UTF_16LE).length * 8);

		System.out.println("length in " + StandardCharsets.UTF_8 + " is " + str1.getBytes(StandardCharsets.UTF_8).length * 8);
	}

}

 

Output

length in ISO-8859-1 is 88
length in US-ASCII is 88
length in UTF-16 is 192
length in UTF-16BE is 176
length in UTF-16LE is 176
length in UTF-8 is 88

  

Previous                                                 Next                                                 Home

No comments:

Post a Comment