ByteBuffer Missing Data When decoded As string

ByteBuffer Missing Data When decoded As string

By : user2185682
Date : November 22 2020, 04:01 AM
it fixes the issue Okay so you are trying to read an int from the Buffer which takes up 4 bits and then trying to get the whole data after reading 4 bits
What I have done is call messageBuffer2.clear(); after reading the int to resolve this issue. here is the full code
code :
byte[] data = new byte[messageBuffer2.limit()];
String dataString = new String(data, StandardCharsets.ISO_8859_1);

Share : facebook icon twitter icon
how to encrypt string data so that it can only be decoded by the computer it resides on?

how to encrypt string data so that it can only be decoded by the computer it resides on?

By : shirin
Date : March 29 2020, 07:55 AM
it helps some times An asymmetric algorithm could be used like so:
The server generates a pair of private/public keys Client asks server (via AJAX) its public key Client encrypts data with the public key Client sends encrypted data to server Server uses private key to decrypt data
Missing some absolute methods on ByteBuffer

Missing some absolute methods on ByteBuffer

By : XYQuadrat
Date : March 29 2020, 07:55 AM
wish of those help One way to get the methods you need is to have a second ByteBuffer sharing the same memory, so you can change its position without changing the position of the original.
Unfortunately, the slice method does not take a position parameter either; instead it uses the current position of the original buffer. So you cannot do:
code :
dstBuffer.slice().position(desiredPosition - dstBuffer.position()).put(srcBuffer);
    srcBuffer.array(), srcBuffer.arrayOffset() + srcBuffer.position(),
    dstBuffer.array(), dstBuffer.arrayOffset() + desiredPosition,
synchronize (lock) {
    int originalPosition = dstBuffer.position();
private static final sun.misc.Unsafe UNSAFE;
static {
    Object result = null;
    try {
        Class<?> klass = Class.forName("sun.misc.Unsafe");
        for (Field field : klass.getDeclaredFields()) {
            if (field.getType() == klass &&
                (field.getModifiers() & (Modifier.FINAL | Modifier.STATIC)) ==
                    (Modifier.FINAL | Modifier.STATIC)) {
                result = field.get(null);
    } catch (Throwable t) {}
    UNSAFE = result == null ? null : (sun.misc.Unsafe)result;

private static final Field ADDRESS_FIELD;
static {
    Field f;
    try {
        f = Buffer.class.getDeclaredField("address");
    } catch (NoSuchFieldException | SecurityException e) {
        f = null;

public static void absolutePut(ByteBuffer dstBuffer, int dstPosition, ByteBuffer srcBuffer) {
    if (!srcBuffer.isDirect()) {
        absolutePut(dstBuffer, dstPosition,
            srcBuffer.array(), srcBuffer.arrayOffset() + srcBuffer.position(),

    if (UNSAFE != null && ADDRESS_FIELD != null && dstBuffer.isDirect()) {
        try {
            long dstAddress = (long)ADDRESS_FIELD.get(dstBuffer) + dstPosition;
            long srcAddress = (long)ADDRESS_FIELD.get(srcBuffer) + srcBuffer.position();
            UNSAFE.copyMemory(srcAddress, dstAddress, srcBuffer.remaining());
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
    } else {
        // fallback to basic loop
        for (int i = srcBuffer.position(); i < srcBuffer.limit(); i++) {
            dstBuffer.put(dstPosition + i, srcBuffer.get(i));

public static void absolutePut(ByteBuffer dstBuffer, int dstPosition, byte[] src, int srcOffset, int length) {
    if (UNSAFE != null && ADDRESS_FIELD != null && dstBuffer.isDirect()) {
        try {
            long dstAddress = (long)ADDRESS_FIELD.get(dstBuffer) + dstPosition;
                src, UNSAFE.arrayBaseOffset(byte[].class) + srcOffset,
                null, dstAddress,
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
    } else {
        // fallback to System.arraycopy
            src, srcOffset,
            dstBuffer.array(), dstBuffer.arrayOffset() + dstPosition,
Can ALL string be decoded as valid binary data?

Can ALL string be decoded as valid binary data?

By : surinder sokhal
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further It depends upon your coding method - some methods use only a limited range of characters so a string containing other characters would not be legal. In Base64 this is the case so the answer is no. With other methods I'm sure its possible but I cannot think of an example other than simply treating the string as binary bytes.
In Javascript, how do I decode a string in which decoded string contains binary (e.g. non UTF-8) data?

In Javascript, how do I decode a string in which decoded string contains binary (e.g. non UTF-8) data?

By : NoSuperstition
Date : March 29 2020, 07:55 AM
I wish this helpful for you Last edit: More publicity should made of this sentence from the 2015 related SO answer
code :
var byteArray = base64js.toByteArray(myBase64Str)
var fs = require('fs')
var base64js =  require('base64-js')
fs.readFile('pathToMyBase64File', 'utf8', (err, data) => { // here 'utf8' is mandatory
  if (err) throw err;
  var byteArray = base64js.toByteArray(data)
  console.log(base64js.byteLength(data) == byteArray.length)
Python - decoded unicode string does not stay decoded

Python - decoded unicode string does not stay decoded

By : user2281336
Date : March 29 2020, 07:55 AM
help you fix your problem Decoding bytes by definition produces "Unicode" (text really, where Unicode is how you can store arbitrary text, so Python uses it internally for all text), so when you say "How can the list contain unicode characters if it has already been decoded?" it betrays a fundamental misunderstanding of what Unicode is. If you have a str in Python 3, it's text, and that text is composed of a series of Unicode code points (with unspecified internal encoding; in fact, modern Python stores in ASCII, latin-1, UCS-2 or UCS-4, depending on highest ordinal value, as well as sometimes caching a UTF-8 representation, or a native wchar representation for use with legacy extension modules).
You're seeing the repr of the nul character (Unicode ordinal 0) and thinking it didn't decode properly, and you're likely right (there's nothing illegal about nul characters, they're just not common in plain text); your input data is almost certainly encoded in UTF-16-LE, not UTF-8. Use the correct codec, and the text comes out correctly:
code :
>>> bs = bytearray(b'I\x00n\x00t\x00e\x00l\x00(\x00R\x00)\x00')
>>> bs.decode('utf-16-le')  # No need to replace things, this is legit UTF-16-LE
>>> list_of_dict = [{'name': _}]
>>> list_of_dict
[{'name': 'Intel(R)'}]
Related Posts Related Posts :
  • Extracting data from HTML and formatting the output
  • SOLR documentCache JMX metrics clarification
  • Limiting Wildfly 14 Two-Way SSL to specific clients
  • How do I get Min and max values to only print when "year" is entered?
  • Hashmap can't loop - getKey() method not found - Using Java 8
  • Android Studio - Create an EditText with a click of a button
  • Mockito Test not invoking verify() method
  • Wrap method implementations of Java interfaces
  • Remediating dynamic SQL into prepared statements
  • Where do X and Y start at in swing windows
  • java code with files work from eclipse but dont work from cmd
  • Return page object from JPA query
  • I can't figure out why this code in my APCS multiple choice book returns 19
  • How to save data between methods
  • I'm trying to install Apache Gobblin. How can I install it using Gradle?
  • Spring Data Sorting Array or Set into Pageable
  • Question about the Java documentation and its implementation
  • How to make a JButton that when pressed it does a new action
  • Java hibernate No validator could be found for boolean
  • Making a POJO Thread Safe
  • Save the data of a text file in a arraylist
  • Sort a List<String[]> by indices using Comparator
  • Overloading in Java for user input?
  • Unable to format timestamp as YYYY-MM-DD HH:mm:ss in java
  • Access SQLite Helper From Adapter
  • How to stream a csv file with header to a HashMap<String, Double> in Java?
  • can't get go daddy ssl certificate to work with spring boot
  • ResourceBundle can't find BaseName gradle project java
  • Java; Jackson; Parsing the array of array json string
  • Java - map key lookup ignoring case
  • Jackson deserialize map null values to empty string
  • Anyone knows why setCount() is not working in twitter4j?
  • Object Visibility in a Multi-threaded Program in Java
  • Can't store and load an arraylist in an object file
  • convert a string number starts with `00` to `+` in java
  • Java - avoiding NonSuchElementException using ConcurrentLinkedDeque
  • Converting Immutable to mutable list Java
  • Getting nosuchmethod exception
  • How to get MQTT subscriptions
  • Android Google Sign in Exceptions
  • JavaFX - method that waits for user input
  • Replacing values for a particular key in treemap changes values for every key
  • This method call passes a null value for a nonnull method parameter. Either the parameter is annotated as a parameter th
  • Kafka: consume all messages on demand
  • Notify what text was changed in textview
  • Tinkerpop/Gremlin: select vertices together with outgoing edge count
  • transform a list of objects into a list of integers that pass a check
  • Why this java code is showing strange behavior?
  • Maven Project classes not compiling
  • Edit image to make text more clear opencv
  • Android Spinner nullpointer
  • Add result to int array every time you finish counting the occurrence
  • Android import java library
  • How to use LDAP Authentication in a corporate environment
  • adding item during iteration in java special usecase
  • How can I sort a map with string key? like (1 foo , 2 foo)
  • How to test an implementation of TLS based on SSLEngine?
  • Sorting a Linked List in alphabetical order
  • Can't make more than one request on java.net.http.HttpClient or will receive: javax.net.ssl.SSLHandshakeException
  • Java logic - strange things happening in while loop
  • shadow
    Privacy Policy - Terms - Contact Us © bighow.org