Enchantments are saved as shorts, but are loaded as and function with integer values
The bug
The game saves natural enchantments as shorts, yet using integer values (eg 32768 (max short + 1)) makes the game load them fine as integers numbers.
Note that the enchantment saving and loading logic exists in multiple methods which all behave differently.
20w07a Mojang names:
- ItemStack.enchant(Enchantment, int): Casts the int enchantment level to byte (-128 to 127) and then stores it as short
- EnchantmentHelper.setEnchantments(...): Casts the int enchantment level to short (-32768 to 32767) and then stores it as short
- EnchantmentHelper.getItemEnchantmentLevel(Enchantment, ItemStack): Reads as int and then clamps it to 0 to 255
- EnchantmentHelper.deserializeEnchantments(ListTag): Reads as int
- EnchantmentHelper.runIterationOnItem(EnchantmentVisitor, ItemStack): Reads as int
- EnchantedBookItem.addEnchantment(ItemStack, EnchantmentInstance): Reads as int, then writes as short
- ItemStack.appendEnchantmentNames(List<Component>, ListTag): Reads as int
How to reproduce
/give @s stick{Enchantments:[{id:"sharpness",lvl:32768}]}- Close and reopen the game
Note that the enchantment level was loaded just fine - Put the stick in an anvil and rename it
The level overflows and becomes -32768