{"id":21513238,"url":"https://github.com/patrickfav/bytes-java","last_synced_at":"2025-04-10T06:14:24.528Z","repository":{"id":53461793,"uuid":"108965147","full_name":"patrickfav/bytes-java","owner":"patrickfav","description":"Bytes is a utility library that makes it easy to create, parse, transform, validate and convert byte arrays in Java. It supports endianness as well as immutability and mutability, so the caller may decide to favor performance.","archived":false,"fork":false,"pushed_at":"2024-12-02T10:38:50.000Z","size":2546,"stargazers_count":164,"open_issues_count":7,"forks_count":34,"subscribers_count":13,"default_branch":"main","last_synced_at":"2025-04-03T03:22:50.143Z","etag":null,"topics":["biginteger","byte-array","bytebuffer","bytes","bytes-java","checksum","encoding","endianness","gzip","hash","java","utility-library"],"latest_commit_sha":null,"homepage":"https://favr.dev/opensource/bytes-java","language":"Java","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/patrickfav.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2017-10-31T08:15:45.000Z","updated_at":"2025-03-20T07:25:55.000Z","dependencies_parsed_at":"2024-12-10T21:01:45.787Z","dependency_job_id":null,"html_url":"https://github.com/patrickfav/bytes-java","commit_stats":null,"previous_names":[],"tags_count":23,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/patrickfav%2Fbytes-java","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/patrickfav%2Fbytes-java/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/patrickfav%2Fbytes-java/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/patrickfav%2Fbytes-java/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/patrickfav","download_url":"https://codeload.github.com/patrickfav/bytes-java/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248166925,"owners_count":21058481,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["biginteger","byte-array","bytebuffer","bytes","bytes-java","checksum","encoding","endianness","gzip","hash","java","utility-library"],"created_at":"2024-11-23T22:55:06.996Z","updated_at":"2025-04-10T06:14:24.490Z","avatar_url":"https://github.com/patrickfav.png","language":"Java","readme":"# Bytes Utility Library for Java\n\nBytes is a utility library that makes it easy to **create**, **parse**, **transform**,\n**validate** and **convert** byte arrays in Java. It's main class `Bytes` is\na collections of bytes and the main API. It supports [endianness](https://en.wikipedia.org/wiki/Endianness)\nas well as **copy-on-write** and **mutable** access, so the caller may decide to favor\nperformance. This can be seen as combination of the features provided by\n[`BigInteger`](https://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html),\n[`ByteBuffer`](https://docs.oracle.com/javase/7/docs/api/java/nio/ByteBuffer.html) but\nproviding a lot of additional features on the micro and macro level of byte arrays (similar to Okio's [ByteString](https://github.com/square/okio)). The main goal is to minimize the need\nto blindly paste code snippets from\n[s](https://stackoverflow.com/questions/140131/convert-a-string-representation-of-a-hex-dump-to-a-byte-array-using-java)\n[t](https://stackoverflow.com/questions/12893758/how-to-reverse-the-byte-array-in-java)\n[a](https://stackoverflow.com/questions/3329163/is-there-an-equivalent-to-memcpy-in-java)\n[c](https://stackoverflow.com/questions/5513152/easy-way-to-concatenate-two-byte-arrays)\n[k](https://stackoverflow.com/questions/1936857/convert-integer-into-byte-array-java)\n[o](https://stackoverflow.com/questions/14243922/java-xor-over-two-arrays)\n[v](https://stackoverflow.com/questions/28997781/bit-shift-operations-on-a-byte-array-in-java)\n[e](https://stackoverflow.com/questions/13109588/base64-encoding-in-java)\n[r](https://stackoverflow.com/questions/2091454/byte-to-inputstream-or-outputstream)\n[f](https://stackoverflow.com/questions/3736058/java-object-to-byte-and-byte-to-object-converter-for-tokyo-cabinet)\n[l](https://stackoverflow.com/questions/4231674/converting-an-array-of-bytes-to-listbyte)\n[o](https://stackoverflow.com/questions/28703273/sorting-byte-arrays-in-numeric-order)\n[w](https://stackoverflow.com/questions/4385623/bytes-of-a-string-in-java)\n[.](https://stackoverflow.com/questions/23360692/byte-position-in-java)\n[c](https://stackoverflow.com/questions/11437203/byte-array-to-int-array)\n[o](https://stackoverflow.com/a/9670279/774398)\n[m](https://stackoverflow.com/questions/1519736/random-shuffling-of-an-array)\n\n[![Maven Central](https://img.shields.io/maven-central/v/at.favre.lib/bytes)](https://mvnrepository.com/artifact/at.favre.lib/bytes)\n[![Github Actions](https://github.com/patrickfav/bytes-java/actions/workflows/build_deploy.yml/badge.svg)](https://github.com/patrickfav/bytes-java/actions)\n[![Javadocs](https://www.javadoc.io/badge/at.favre.lib/bytes.svg)](https://www.javadoc.io/doc/at.favre.lib/bytes)\n[![Coverage](https://sonarcloud.io/api/project_badges/measure?project=patrickfav_bytes-java\u0026metric=coverage)](https://sonarcloud.io/summary/new_code?id=patrickfav_bytes-java)\n[![Maintainability Rating](https://sonarcloud.io/api/project_badges/measure?project=patrickfav_bytes-java\u0026metric=sqale_rating)](https://sonarcloud.io/summary/new_code?id=patrickfav_bytes-java)\n[![Reliability Rating](https://sonarcloud.io/api/project_badges/measure?project=patrickfav_bytes-java\u0026metric=reliability_rating)](https://sonarcloud.io/summary/new_code?id=patrickfav_bytes-java)\n\nIts main features include:\n\n* **Creation** from a wide variety of sources: multiple arrays, integers, [streams](https://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html), random, strings, files, uuid, ...\n* **Transformation** with many built-in: append, [xor](https://en.wikipedia.org/wiki/Exclusive_or), [and](https://en.wikipedia.org/wiki/Logical_conjunction), [hash](https://en.wikipedia.org/wiki/Cryptographic_hash_function), [shifts](https://en.wikipedia.org/wiki/Bitwise_operation#Bit_shifts), shuffle, reverse, [checksum](https://en.wikipedia.org/wiki/Checksum), ...\n* **Validators** with the ability to arbitrarily combine multiple ones with logical expressions\n* **Parsing and Encoding** in most common binary-to-text-encodings: [hex](https://en.wikipedia.org/wiki/Hexadecimal), [base32](https://en.wikipedia.org/wiki/Base32), [base64](https://en.wikipedia.org/wiki/Base64), ...\n* **Immutable, Mutable and Read-Only** versions\n* **Handling Strings** with encoding and normalizing strings for arbitrary charset\n* **Utility Features** like `indexOf`, `count`, `isEmpty`, `bitAt`, `contains` ...\n* **Flexibility** provide your own Transformers, Validators and Encoders\n\nThe code is compiled with target [Java 7](https://en.wikipedia.org/wiki/Java_version_history#Java_SE_7) to keep backwards compatibility with *Android* and older *Java* applications.\nIt is lightweight as it does not require any additional dependencies.\n\n## Quickstart\n\nAdd dependency to your `pom.xml` ([check latest release](https://github.com/patrickfav/bytes-java/releases)):\n\n```xml\n\u003cdependency\u003e\n    \u003cgroupId\u003eat.favre.lib\u003c/groupId\u003e\n    \u003cartifactId\u003ebytes\u003c/artifactId\u003e\n    \u003cversion\u003e{latest-version}\u003c/version\u003e\n\u003c/dependency\u003e\n```\n\n_Note:_ There is a byte-code optimized version (powered by [ProGuard](https://www.guardsquare.com/en/products/proguard)) which can be used with [classifier](https://maven.apache.org/pom.html#Maven_Coordinates) 'optimized'. This may have issues so use at your own risk.\n\nSome simple examples:\n\n```java\nBytes b = Bytes.wrap(someByteArray);  //reuse given reference\nb.copy().reverse(); //reverse the bytes on a copied instance\nString hex = b.encodeHex(); //encode base16/hex\n```\n\n```java\nBytes b = Bytes.parseHex(\"0ae422f3\");  //parse from hex string\nint result = b.toInt(); //get as signed int\n```\n\n```java\nBytes b = Bytes.from(array1);  //create from copy of array1\nb.resize(2).xor(array2); //shrink to 2 bytes and xor with other array\nbyte[] result = b.array(); //get as byte array\n```\n\n## API Description\n\nPer default the instance is **semi-immutable**, which means any transformation will\ncreate a copy of the internal array (it is, however, possible to get and\nmodify the internal array). There is a **mutable** version which supports\nin-place modification for better performance and a **read-only** version which\nrestricts the access to the internal array.\n\n### Constructors\n\nThere are 3 basic constructors:\n\n * `wrap()` which reuses the given array reference; this is equivalent to `ByteBuffer.wrap()`\n * `from()` which always creates a new internal array reference (i.e. a copy of the passed reference)\n * `parse()` which parses from binary-text-encoded strings (see other section)\n\nHere is a simple example to show the difference:\n\n```java\nbyte[] myArray = ...\nBytes bWrap = Bytes.wrap(myArray);\nassertSame(myArray, bWrap.array());\n\nbyte[] myArray2 = ...\nBytes bFrom = Bytes.from(myArray2);\nassertNotSame(myArray2, bFrom.array());\nassertArrayEquals(myArray2, bFrom.array());\n```\n\nThe following code is equivalent:\n\n```java\nBytes.wrap(myArray).copy() ~ Bytes.from(myArray)\n```\n\n#### More Constructors\n\nFor a **null-safe version**, which uses the empty array in case of a null byte array:\n\n```java\nBytes.wrapNullSafe(null);\nBytes.fromNullSafe(null);\n```\n\n**Concatenating** of multiple byte arrays or bytes:\n\n```java\nBytes.from(array1, array2, array3);\nBytes.from((byte) 0x01, (byte) 0x02, (byte) 0x03);\n```\n\nCreating byte arrays from **primitive integer** types and arrays:\n\n```java\nBytes.from(8);  //00000000 00000000 00000000 00001000\nBytes.from(1897621543227L);\nBytes.from(1634, 88903, 77263);\nBytes.from(0.7336f, -87263.0f);\nBytes.from(0.8160183296, 3984639846.0);\n```\n\nInitializing **empty arrays** of arbitrary length:\n\n```java\nBytes.allocate(16);\nBytes.allocate(4, (byte) 1); //fill with 0x01\nBytes.empty(); //creates zero length byte array\n```\n\nCreating cryptographically secure **random** byte arrays:\n\n```java\nBytes.random(12);\n```\n\nCreating cryptographically unsecure **random** byte arrays for e.g. testing:\n\n```java\nBytes.unsecureRandom(12, 12345L); // using seed makes it deterministic\n```\n\nReading byte content of encoded `String`s:\n\n```java\nBytes.from(utf8String)\nBytes.from(utf8StringToNormalize, Normalizer.Form.NFKD) //normalizes unicode\nBytes.from(asciiString, StandardCharset.US_ASCII) //any charset\n```\n\nAnd other types:\n\n```java\nBytes.from(byteInputStream); //read whole java.io.InputStream\nBytes.from(byteInputStream, 16); //read java.io.InputStream with length limitation\nBytes.from(byteList); //List\u003cByte\u003e byteList = ...\nBytes.from(myBitSet); //java.util.BitSet myBitSet = ...\nBytes.from(bigInteger); //java.math.BigInteger\nBytes.from(file); //reads bytes from any java.io.File\nBytes.from(dataInput, 16); //reads bytes from any java.io.DataInput\nBytes.from(UUID.randomUUID()); //read 16 bytes from UUID\n```\n\nFor parsing binary-text-encoded strings, see below.\n\n### Transformers\n\nTransformers transform the internal byte array. It is possible to create\ncustom transformers if a specific feature is not provided by the default\n implementation (see `BytesTransformer`). Depending on the type (mutable vs\n immutable) and transformer it will overwrite the internal byte array\n or always create a copy first.\n\n```java\nBytes result = Bytes.wrap(array1).transform(myCustomTransformer);\n```\n\n#### Built-In Transformers\n\nFor **appending** byte arrays or primitive integer types to current instances.\n*Note:* this will create a new copy of the internal byte array; for dynamically\n growing byte arrays see `ByteArrayOutputStream`.\n\n```java\nBytes result = Bytes.wrap(array1).append(array2);\nBytes result = Bytes.wrap(array1).append(1341);\nBytes result = Bytes.wrap(array1).append((byte) 3);\nBytes result = Bytes.wrap(array1).append(\"some string\");\n```\n\n**Bitwise operations**: XOR, OR, AND, NOT as well as left and right shifts and switching bits:\n\n```java\nBytes.wrap(array).xor(array2); // 0010 0011 xor() 1011 1000 = 1001 1011\nBytes.wrap(array).or(array2); // 0010 0011 or() 1101 0100 = 1111 0111\nBytes.wrap(array).and(array2); // 0010 0011 and() 1011 1000 = 0010 0000\nBytes.wrap(array).not(); // 0010 0011 negate() = 1101 1100\nBytes.wrap(array).leftShift(8);\nBytes.wrap(array).rightShift(8);\nBytes.wrap(array).switchBit(3, true);\n```\n\n**Copy** operations, which copies the internal byte array to a new instance:\n\n```java\nBytes copy = Bytes.wrap(array).copy();\nBytes copy = Bytes.wrap(array).copy(3, 17); //copy partial array\n```\n\n**Resizing** the internal byte array:\n\n```java\nBytes resized = Bytes.wrap(array).resize(3); //from {3, 9, 2, 1} to {9, 2, 1}\n```\n\n**Hashing** the internal byte array using the [`MessageDigest`](https://docs.oracle.com/javase/7/docs/api/java/security/MessageDigest.html) Java crypto API:\n\n```java\nBytes hash = Bytes.wrap(array).hashSha256();\nBytes hash = Bytes.wrap(array).hashSha1();\nBytes hash = Bytes.wrap(array).hashMd5();\nBytes hash = Bytes.wrap(array).hash(\"SHA-512\");\n```\n\n**Reversing** of the byte order in the array\n\n```java\nBytes result = Bytes.wrap(array).reverse();\n```\n\n#### Additional Transformers\n\nMore transformers can be accessed through the `BytesTransformers`, which\ncan be statically imported for a less verbose syntax:\n\n```java\nimport static at.favre.lib.bytes.BytesTransformers.*;\n```\n\n**HMAC** used to calculate [keyed-hash message authentication code](https://en.wikipedia.org/wiki/HMAC):\n\n```java\nBytes.wrap(array).transform(hmacSha256(macKey32Byte));\nBytes.wrap(array).transform(hmacSha1(macKey20Byte));\nBytes.wrap(array).transform(hmac(macKey16Byte,\"HmacMd5\"));\n```\n\n**Checksum** can be calculated or automatically appended:\n\n```java\nBytes.wrap(array).transform(checksumAppendCrc32());\nBytes.wrap(array).transform(checksumCrc32());\nBytes.wrap(array).transform(checksum(new Adler32(), ChecksumTransformer.Mode.TRANSFORM, 4));\n```\n\n**GZip compression** is supported by [`GZIPInputStream`](https://docs.oracle.com/javase/7/docs/api/java/util/zip/GZIPInputStream.html):\n\n```java\nBytes compressed = Bytes.wrap(array).transform(compressGzip());\nBytes decompressed = compressed.transform(decompressGzip());\n```\n\n**Sorting** of individual bytes with either [`Comparator`](https://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html) or natural order:\n\n```java\nBytes.wrap(array).transform(sort()); // 0x00 sorts after 0xff\nBytes.wrap(array).transform(sortUnsigned()); // 0xff sorts after 0x00\nBytes.wrap(array).transform(sort(byteComparator));\n```\n\n**Shuffling** of individual bytes:\n\n```java\nBytes.wrap(array).transform(shuffle());\n```\n\n### Parser and Encoder for Binary-Text-Encodings\n\nThis library can parse and encode a variety of encodings: binary, decimal, [octal](https://en.wikipedia.org/wiki/Octal),\n[hex](https://en.wikipedia.org/wiki/Hexadecimal) and\n[base64](https://en.wikipedia.org/wiki/Base64). Additionally custom parsers are supported by providing your own\nimplementation:\n\n```java\nBytes.parse(\"8sK;S*j=r\", base85Decoder);\nBytes.encode(base85Encoder);\n ```\n\n**Hex** can be upper and lowercase and also supports `0x` prefix for parsing:\n\n```java\nBytes.parseHex(\"a0e13eaa1a\")\nBytes.parseHex(\"0xA0E1\")\n\nBytes.from(array).encodeHex() //a0e13eaa1a\n ```\n\nThis lib has it's own build in **Base64** encoder:\n\n```java\nBytes.parseBase64(\"SpT9/x6v7Q==\");\n\nBytes.from(array).encodeBase64(); //\"SpT9/x6v7Q==\"\nBytes.from(array).encodeBase64Url(); //\"SpT9_x6v7Q==\"\n ```\n\nalso a **Base32** encoder (using the RFC4648 non-hex alphabet):\n\n```java\nBytes.parseBase32(\"MZXQ====\");\nBytes.from(array).encodeBase32();\n ```\n\nAdditionally the following radix encodings are supported:\n\n```java\nBytes.from(array).encodeBinary(); //1110110110101111\nBytes.from(array).encodeDec(); //20992966904426477\nBytes.from(array).encodeOctal(); //1124517677707527755\nBytes.from(array).encodeRadix(36); //5qpdvuwjvu5\n```\n\n### Handling Strings\n\nYou can easily get the **UTF-8 encoded version** of a string with\n\n```java\nString s = \"...\";\nBytes.from(s);\n```\n\nor get the **[normalized version](https://en.wikipedia.org/wiki/Unicode_equivalence)**,\nwhich is the recommended way to convert e.g. user names\n\n```java\nString pwd = \"ℌH\";\nBytes.from(pwd, Normalizer.Form.NFKD); //would be \"HH\" normalized\n```\n\nor get as any other **[character encodings](https://en.wikipedia.org/wiki/Character_encoding)**\n\n```java\nString asciiString = \"ascii\";\nBytes.from(asciiString, StandardCharsets.US_ASCII);\n```\n\nTo easily append a string to an byte array you can do\n\n```java\nString userPwdHash = ...;\nBytes.from(salt).append(userPwd).hashSha256();\n```\n\n### Utility Methods\n\nMethods that return additional information about the instance.\n\nFinding occurrence of specific bytes:\n\n```java\nBytes.wrap(array).contains((byte) 0xE1);\nBytes.wrap(array).indexOf((byte) 0xFD);\nBytes.wrap(array).indexOf(new byte[] {(byte) 0xFD, 0x23});\nBytes.wrap(array).indexOf((byte) 0xFD, 5); //search fromIndex 5\nBytes.wrap(array).lastIndexOf((byte) 0xAE);\nBytes.wrap(array).startsWith(new byte[] {(byte) 0xAE, 0x32});\nBytes.wrap(array).endsWidth(new byte[] {(byte) 0xAE, 0x23});\n```\n\nLength checks:\n\n```java\nBytes.wrap(array).length();\nBytes.wrap(array).lengthBit(); //8 * array.length\nBytes.wrap(array).isEmpty();\n```\n\nAccessing part of the array as primitives from arbitrary position:\n\n```java\nBytes.wrap(array).bitAt(4); // 0010 1000 -\u003e false\nBytes.wrap(array).byteAt(14); // 1111 1111 -\u003e -1\nBytes.wrap(array).unsignedByteAt(14); // 1111 1111 -\u003e 255\nBytes.wrap(array).intAt(4);\nBytes.wrap(array).longAt(6);\n```\n\nAnd others:\n\n```java\nBytes.wrap(array).count(0x01); //occurrences of 0x01\nBytes.wrap(array).count(new byte[] {0x01, 0xEF}); //occurrences of pattern [0x01, 0xEF]\nBytes.wrap(array).entropy();\n```\n\nOf course all standard Java Object methods are implemented including:\n`hashCode()`, `equals()`, `toString()` as well as it being\n[`Comparable`](https://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html).\nIn addition there is a constant time `equalsConstantTime()` method, see [here](https://codahale.com/a-lesson-in-timing-attacks/) why this\nmight be useful.\n\nThe `toString()` methods only shows the length and a preview of maximal 8 bytes:\n\n```\n16 bytes (0x7ed1fdaa...12af000a)\n```\n\nBytes also implements the `Iterable` interface, so it can be used in a\nforeach loop:\n\n```java\nfor (Byte aByte : bytesInstance) {\n    ...\n}\n```\n\nThe `equals` method has overloaded versions for `byte[]`, `Byte[]` and `ByteBuffer` which can be used to directly\ncompare the inner array:\n\n```java\nbyte[] primitiveArray1 = ...\nbyte[] primitiveArray2 = ...\nBytes.wrap(primitiveArray1).equals(primitiveArray2); //compares primitiveArray1 with primitiveArray2\n```\n\n### Validation\n\nA simple validation framework which can be used to check the internal byte array:\n\n```java\nimport static at.favre.lib.bytes.BytesValidators.*;\n\nBytes.wrap(new byte[]{8, 3, 9}).validate(startsWith((byte) 8), atLeast(3)); // true\n```\n\nThis is especially convenient when combining validators:\n\n```java\nBytes.wrap(new byte[]{0, 1}).validate(atMost(2), notOnlyOf((byte)  0)); // true\n```\n\nValidators also support nestable logical expressions AND, OR as well as NOT:\n\n```java\nBytes.allocate(0).validate(or(exactLength(1), exactLength(0))) //true\nBytes.allocate(19).validate(and(atLeast(3), atMost(20))) //true\nBytes.allocate(2).validate(not(onlyOf((byte) 0))); //false\n```\n\nNesting is also possible:\n\n```java\nassertTrue(Bytes.allocate(16).validate(\n                or(\n                   and(atLeast(8),not(onlyOf(((byte) 0)))),\n                   or(exactLength(16), exactLength(12))))); // true\n```\n\n### Converting\n\nThe internal byte array can be converted or exported into many different formats.\nThere are 2 different kinds of converters:\n\n* Ones that create a new type which **reuses the same shared memory**\n* Ones that create a **copy** of the internal array, which start with `to*`\n\n#### Shared Memory Conversion\n\nNot technically a conversation, but it is of course possible to access the internal array:\n\n```java\nBytes.wrap(array).array();\n```\n\nConversion to [`InputStream`](https://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html)\n and [`ByteBuffer`](https://docs.oracle.com/javase/7/docs/api/java/nio/ByteBuffer.html):\n\n```java\nBytes.wrap(array).inputStream();\nBytes.wrap(array).buffer();\n```\n\nIf you just want a duplicated instance, sharing the same array:\n\n```java\nBytes.wrap(array).duplicate();\n```\n\nFor the conversion to read-only and mutability, see below.\n\n#### Copy Conversion\n\nTo primitives (if the internal array is not too long)\n\n```java\nBytes.wrap(array).toByte();\nBytes.wrap(array).toUnsignedByte();\nBytes.wrap(array).toInt();\nBytes.wrap(array).toDouble();\n```\n\nTo primitive arrays\n\n```java\nBytes.wrap(array).toIntArray(); // of type int[]\nBytes.wrap(array).toLongArray(); // of type long[]\n```\n\nTo other collections\n\n```java\nBytes.wrap(array).toList(); // of type List\u003cByte\u003e\nBytes.wrap(array).toBoxedArray(); // of type Byte[]\nBytes.wrap(array).toBitSet(); //of type java.util.BitSet\n```\n\nto [`BigInteger`](https://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html) of course\n\n```java\nBytes.wrap(array).toBigInteger();\n```\n\nand others\n\n```java\nBytes.wrap(array).toUUID(); // convert 16 byte to UUID\nBytes.wrap(array).toCharArray(StandardCharsets.UTF-8); // converts to encoded char array\n```\n\n### Mutable and Read-Only\n\nPer default the instance is immutable, i.e. every transformation will create a\na new internal byte array (very similar to the API of `BigInteger`). While\nthis is usually the default way to design such a construct because it shows\n[various advantages](https://softwareengineering.stackexchange.com/questions/151733/if-immutable-objects-are-good-why-do-people-keep-creating-mutable-objects)\nthis can introduce a major performance issue when handling big arrays\nor many transformations.\n\n#### Mutable Bytes\n\nAll transformers (if possible) reuse or overwrite the same internal memory\nto avoid unneeded array creation to minimize time and space complexity.\nTo create a mutable instance just do:\n\n```java\nMutableBytes b = Bytes.from(array).mutable();\n```\n\nMutable classes also enable further APIs for directly modify the internal array:\n\n```java\nb.setByteAt(3, (byte) 0xF1)\nb.overwrite(anotherArray) //directly overwrite given array\nb.fill(0x03) // fills with e.g. 3\nb.wipe() //fills with zeros\nb.secureWipe() //fills with random data\n```\n\nCreate a immutable version again with:\n\n```java\nBytes b2 = b.immutable();\n```\n\n*Note:* a copy will inherit mutability/read-only properties:\n\n```java\nBytes b = Bytes.from(array).mutable().copy();\nassertTrue(b.isMutable());\n```\n\n##### AutoClosable for try-with-resources\n\nIn security-relevant environments it is best practice to wipe the memory of secret data, such as\nsecret keys. This can be used with Java 7 feature try-with-resource like this:\n\n```java\ntry (MutableBytes b = Bytes.wrap(aesBytes).mutable()) {\n    SecretKey s = new SecretKeySpec(b.array(), \"AES\");\n    ...\n}\n```\n\n#### Readonly Bytes\n\nOn the other hand, if you want a export a instance with limited access,\nespecially no easy way to alter the internal byte array, read-only instances\nmay be created by:\n\n```java\nBytes b = Bytes.from(array).readOnly();\n```\n\nEvery call to the following conversation methods will throw a `ReadOnlyBufferException`:\n\n```java\nreadOnlyBytes.array();\nreadOnlyBytes.byteBuffer();\nreadOnlyBytes.inputStream();\n```\n\n## Download\n\nThe artifacts are deployed to [Maven Central](https://search.maven.org/).\n\n### Maven\n\nAdd the dependency of the [latest version](https://github.com/patrickfav/bytes-java/releases) to your `pom.xml`:\n\n```xml\n\u003cdependency\u003e\n    \u003cgroupId\u003eat.favre.lib\u003c/groupId\u003e\n    \u003cartifactId\u003ebytes\u003c/artifactId\u003e\n    \u003cversion\u003e{latest-version}\u003c/version\u003e\n\u003c/dependency\u003e\n```\n\n### Gradle\n\nAdd to your `build.gradle` module dependencies:\n\n    implementation group: 'at.favre.lib', name: 'bytes', version: '{latest-version}'\n\n### Local Jar Library\n\n[Grab jar from latest release.](https://github.com/patrickfav/bytes-java/releases/latest)\n\n### OSGi\n\nThe library should be prepared to be used with the OSGi framework with the help of the [bundle plugin](http://felix.apache.org/documentation/subprojects/apache-felix-maven-bundle-plugin-bnd.html).\n\n\n## Digital Signatures\n\n### Signed Jar\n\nThe provided JARs in the Github release page are signed with my private key:\n\n    CN=Patrick Favre-Bulle, OU=Private, O=PF Github Open Source, L=Vienna, ST=Vienna, C=AT\n    Validity: Thu Sep 07 16:40:57 SGT 2017 to: Fri Feb 10 16:40:57 SGT 2034\n    SHA1: 06:DE:F2:C5:F7:BC:0C:11:ED:35:E2:0F:B1:9F:78:99:0F:BE:43:C4\n    SHA256: 2B:65:33:B0:1C:0D:2A:69:4E:2D:53:8F:29:D5:6C:D6:87:AF:06:42:1F:1A:EE:B3:3C:E0:6D:0B:65:A1:AA:88\n\nUse the jarsigner tool (found in your `$JAVA_HOME/bin` folder) folder to verify.\n\n### Signed Commits\n\nAll tags and commits by me are signed with git with my private key:\n\n    GPG key ID: 4FDF85343912A3AB\n    Fingerprint: 2FB392FB05158589B767960C4FDF85343912A3AB\n\n## Build\n\n### Jar Sign\n\nIf you want to jar sign you need to provide a file `keystore.jks` in the\nroot folder with the correct credentials set in environment variables (\n`OPENSOURCE_PROJECTS_KS_PW` and `OPENSOURCE_PROJECTS_KEY_PW`); alias is\nset as `pfopensource`.\n\nIf you want to skip jar signing just change the skip configuration in the\n`pom.xml` jar sign plugin to true:\n\n    \u003cskip\u003etrue\u003c/skip\u003e\n\n### Build with Maven\n\nUse the Maven wrapper to create a jar including all dependencies\n\n    mvnw clean install\n\n### Checkstyle Config File\n\nThis project uses my [`common-parent`](https://github.com/patrickfav/mvn-common-parent) which centralized a lot of\nthe plugin versions as well as providing the checkstyle config rules. Specifically they are maintained in [`checkstyle-config`](https://github.com/patrickfav/checkstyle-config). Locally the files will be copied after you `mvnw install` into your `target` folder and is called\n`target/checkstyle-checker.xml`. So if you use a plugin for your IDE, use this file as your local configuration.\n\n## Tech Stack\n\n* Java 7 Source, JDK 11 required to build (not yet JDK17 compatible)\n* Maven 3\n\n# Credits\n\n* Byte util methods derived from `primitives.Bytes` from [Google Guava](https://github.com/google/guava) (Apache v2)\n* Entropy class derived from [Twitter Commons](https://github.com/twitter/commons) (Apache v2)\n* Base64 implementation and some util methods from [Okio](https://github.com/square/okio) (Apache v2)\n\n# License\n\nCopyright 2017 Patrick Favre-Bulle\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpatrickfav%2Fbytes-java","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fpatrickfav%2Fbytes-java","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpatrickfav%2Fbytes-java/lists"}