简体   繁体   中英

How do I check if a Uint8Array is an encoded string?

I'm looking for the following function that's fast and simple, whereby the input can either be raw data or an encoded string (using TextEncoder ):

function isString(data: Uint8Array): boolean {
  ...
}

Raw binary data is just bits and bytes. And those bytes could be interpreted as string if you want, but you have no way of knowing if that is correct and what the author of that data intended.

For example:

const binary = 0b01000001; // one byte
console.log(binary) // 65
console.log(String.fromCharCode(binary)) // "A"

That byte could be interpreted as a number, or as a string. And if all you have is that one byte then you cannot possibly know what the intent of that data would be.


A file, in comparison, has a standardized wrapper which contains structured data about the file, as well possibly a name with an extension that provides a hint about how to process that data. Somewhere in that structure is the actual raw data.

So this is a very different sort of thing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM