In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "what are the binary-related data types". In the daily operation, I believe that many people have doubts about the binary-related data types. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the doubts about "what are the binary-related data types?" Next, please follow the editor to study!
Binary conversion diagram
Binary related data type
Before introducing the common binary data processing, let's briefly introduce the following binary-related data types
ArrayBuffer & & TypedArray
TypedArray is a new class array data structure that describes binary data added by ES6+. But it itself cannot be instantiated or even accessed. You can think of it as Abstract Class or Interface. Based on TypedArray, there are the following data types:
Uint8ArrayUint and Unsigned Int represent each item of the array is unsigned integer 8 represents each item of data occupies 8 bits, that is, one byte
Int8Array
Uint16Array
Int16Array
...
Through Uint8Array, you can know the meaning represented by Uint16Array,Int8Array.
Const array = new Int32Array ([1,2,3]) / / .length represents the size of the array / / 3 array.length / / .btyeLength represents the size of bytes occupied by the data / / 12 array.byteLength
ArrayBuffer stands for binary data structure, "and read-only", which needs to be converted to TypedArray for write operations.
Const array = new Int16Array ([1,2,3]) / / TypedArray-> ArrayBuffer array.buffer / / ArrayBuffer-> TypedArray new Int16Array (array.buffer) / / buffer.length represents the size of bytes occupied by the data array.buffer.length = array.byteLength
Connect multiple TypedArray
TypedArray does not have an Array.prototype.concat method like an array to join multiple TypedArray. However, it provides TypedArray.prototype.set that can be used to connect strings indirectly.
❝can refer to the MDN document: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/set ❞
/ / place typedarray typedarray.set (typedarray, offset) at the displacement offset position
The principle is to allocate a piece of space enough to accommodate the TypedArray that needs to be connected, and then stack it one by one at the corresponding location.
Function concatenate (constructor,... arrays) {let length = 0; for (let arr of arrays) {length + = arr.length;} let result = new constructor (length); let offset = 0; for (let arr of arrays) {result.set (arr, offset); offset + = arr.length;} return result;} concatenate (Uint8Array, new Uint8Array ([1,2,3]), new Uint8Array ([4,5,6]))
At the same time, you also need to have a general understanding of how to obtain resources, such as XHR,fetch, uploading through files.
Blob
Blob is a class file object on the browser side. Manipulating Blob requires the use of the data type FileReader.
FileReader has the following methods to convert Blob into other data
FileReader.prototype.readAsArrayBuffer
FileReader.prototype.readAsText
FileReader.prototype.readAsDataURL
FileReader.prototype.readAsBinaryString
Const blob = new Blob ('hello'.split (')) / / indicates the file size blob.size const array = new Uint8Array ([128,128,128]) const blob2 = new Blob ([array]) function readBlob (blob) Type) {return new Promise (resolve = > {const reader = new FileReader () reader.onload = function (e) {resolve (e.target.result)} reader.readAsArrayBuffer (blob)})} readBlob (blob, 'DataURL') .then (url = > console.log (url))
Data input
Requests for data input or resources can be divided into the following two ways
Request network resources through an url address
Request local resources through file upload
Fetch
Fetch should be familiar to everyone, but most of them are used in a single environment and are generally used to request json data. In fact, "it can also set the format of returned data to Blob or ArrayBuffer." "
Fetch returns a Promise,Response containing a Response object with the following methods
Response.prototype.arrayBuffer
Response.prototype.blob
Response.prototype.text
Response.prototype.json
For more information on ❝, please see the MDN documentation, https://developer.mozilla.org/en-US/docs/Web/API/Response ❞.
Fetch ('/ api/ping') .then (res = > {/ / true console.log (res instanceof Response) / / the most common use of return res.json () / / return Blob / / return res.blob () / / return ArrayBuffer / / return res.arrayBuffer ()})
In addition, the omnipotent Response API can use TypedArray,Blob,Text as both input and output.
"this means that the conversion of these three data types can be done through Response."
Xhr
"xhr can set responseType to receive the appropriate data type"
Const request = new XMLHttpRequest () request.responseType = 'arraybuffer' request.responseType =' blob'
File
Local files can be uploaded via input [type=file].
When the upload is successful, the uploaded file can be obtained through document.getElementById ('input'). Files [0], that is, a File object, which is a subclass of Blob, and the file content can be obtained through FileReader or Response.
Data output
Or data display or download, the data can be represented by url after binary processing, and then referenced or downloaded directly through image, video and other elements.
Data URL
Data URL is Data As URL. Therefore, "if the resources are too large, the address will be very long. "it is expressed in the following form.
Data: [] [; base64]
Let's start with a hello world. Paste the following address into the address bar and you will access hello, world
Data:text/html,Hello%2C%20World!
Base64 encoding and decoding
Base64 uses uppercase and lowercase letters, numbers, + and / 64 characters to encode data, so it is called Base64. After encoding, the size of the text will become larger.
In browsers, you can use atob and btoa encoding to decode data.
/ / aGVsbG8= btoa ('hello')
Object URL
You can use the browser's new API URL object to generate an address to represent the Blob data.
/ / paste the generated address to access hello, world / / blob: http://host/27254c37-db7a-4f2f-8861-0cf9aec89a64 URL.createObjectURL (new Blob ('hello, world'.split (')
download
Data:application/octet-stream;base64,5bGx5pyI
Resources can be downloaded using FileSaver [1].
Here also simply write a function to download a link
Function download (url, name) {const a = document.createElement ('a') a.download = name a.rel = 'noopener' a.href = url / / trigger Simulation Click a.dispatchEvent (new MouseEvent (' click')) / / or a.click (}
Binary data conversion
Binary data conversion
The above is the conversion diagram between binary data. Some transformations can be done directly through API, while others require code. Here are some common conversion codes.
String to TypedArray
According to the figure above, the conversion from string to TypedArray can be done through the path of "String-> Blob-> ArrayBuffer-> TypedArray".
About the function readBlob in the code can flip back the link data type-Blob [2]
Const name = 'mountain moon' const blob = new Blob (name.split (')) readBlob (blob, 'ArrayBuffer'). Then (buffer = > new Uint8Array (buffer))
You can also convert "String-> ArrayBuffer-> TypedArray" directly through Response API.
Const name = 'mountain moon' new Response (name) .arrayBuffer (buffer = > new Uint8Array (buffer))
Both of the above methods are converted directly through API, if you are more likely to know how to manually convert a string and binary TypedArray
String to TypedArray 2
Use enodeURIComponent to convert the string to utf8, and then construct TypedArray.
Function stringToTypedArray (s) {const str = encodeURIComponent (s) const binstr = str.replace (/% ([0-9A-F] {2}) / g, (_, p1) = > {return String.fromCharCode ('0x' + p1)}) return new Uint8Array (binstr.split ('') .map (x = > x.charCodeAt (0))}
Practice
1. How to upload local pictures and display them on a web page
The way is obtained from the conversion diagram arranged above.
Upload pictures locally-> Blob-> Object URL
two。 How to splice two audio files
The way is obtained from the conversion diagram arranged above.
Fetch requests audio resources-> ArrayBuffer-> TypedArray-> spliced into a TypedArray-> ArrayBuffer-> Blob-> Object URL
3. How to convert json data to demo.json and download files
Json is regarded as a string, which is derived from the conversion diagram sorted out above.
Text-> DataURL
In addition to using DataURL, you can also convert it to Object URL for download. For the downloaded function download, please refer to the data output of the above link-download [3]
Text-> Blob-> Object URL
You can paste the following code directly into the console download file
Const json = {a: 3, b: 4, c: 5} const str = JSON.stringify (json, null, 2) / / Scheme 1: Text-> DataURL const dataUrl = `data:,$ {str} `download (dataUrl, 'demo.json') / / option 2: Text-> Blob-> ObjectURL const url = URL.createObjectURL (new Blob (str.split (')) download (url, 'demo1.json') so far The study on "what are the binary-related data types" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.