setUint8() writes one byte into a DataView. The value is stored as an unsigned 8-bit integer, a whole number from 0 to 255, at the byte offset you pass first. It is the basic “put this byte here” tool for building binary data by hand, such as file signatures, colour values or protocol headers. Values outside 0 to 255 wrap around (256 becomes 0, -1 becomes 255), and the method returns undefined.
Call setUint8() on a DataView object with a byte position and the value to write.
JavaScript
dataview.setUint8(byteOffset, value)
Call
What it does
view.setUint8(byteOffset, value)
Converts value to a unsigned 8-bit integer (0 to 255) and writes it into the byte at byteOffset. Returns undefined.
view.setUint8(i, 0)
Clears byte i, for example inside a loop that resets a buffer to zeros.
Part of the original DataView from ES2015, so every modern browser and runtime has it. With one byte there is no byte order to choose, so setUint8() has no littleEndian argument.
Library declarations
JavaScript
DataView.prototype.setUint8(byteOffset, value)
// returns undefined; writes 1 byte starting at byteOffset
// value is converted to a unsigned 8-bit integer
// needs byteOffset < view.byteLength, else RangeError
Parameters
Parameter
Description
byteOffset
Where to start writing, counted in bytes from the start of the view (not of the underlying buffer). It is converted to a whole number, so 1.9 means 1 and "2" means 2. It must be smaller than view.byteLength. A negative or too-large offset throws a RangeError.
value
The number to store. It is converted to a Number, the fraction is cut off (3.9 becomes 3, -3.9 becomes -3), and the result wraps around modulo 256 into 0 to 255. NaN and Infinity are stored as 0.
Return Value
Return Value
Description
undefined
setUint8() gives nothing back. Its result is the 1 byte it changed inside the buffer; read them back with getUint8().
JavaScript Examples
Example 1 — Write an IPv4 Address Byte by Byte
An IPv4 address has four parts from 0 to 255, so each part fits in one byte. Write them, then read the 4 bytes as one number.