java - What is the purpose of low and high nibble when converting a string to a HexString
问题描述
Recently I have been going through some examples of MD5 to start getting an understanding of security and MD5 has been fairly simple to understand for the most part and a good starting point even though it is no longer secure. Despite this I have a question regarding high and lo nibbles when it comes to converting a string to a hex string.
So I know high and low nibbles are equal to half a byte or also can be hex digits that represent a single hexadecimal digit. What I am not understanding though is exactly how they work and the purpose that they serve. I have been searching on google and I can't find much of an answer that will help explain what they do in the context that they are in. Here is the context of the conversion:
private static String toHexString( byte[] byteArray )
{
final String HEX_CHARS = "0123456789ABCDEF";
byte[] result = new byte[byteArray.length << 1];
int len = byteArray.length;
for( int i = 0 ; i < len ; i++ )
{
byte b = byteArray[i]
int lo4 = b & 0x0F;
int hi4 = ( b & 0xF0 ) >> 4;
result[i * 2] = (byte)HEX_CHARS.charAt( hi4 );
result[i * 2 + 1] = (byte)HEX_CHARS.charAt( lo4 );
}
return new String( result );
}
I don't exactly understand what is going on in the for statement. I would appreciate any help understanding this and if there is some link to some places that I can learn more about this please also leave it.
I understand the base definition of nibble but not the operations and what the assignment to the number 4 is doing either.
If I need to post the full example code I will just ask as I am unsure if it is needed.
解决方案
此代码只是将字节数组转换为十六进制表示。在for
-loop 中,每个字节都被转换为两个字符。我认为通过一个例子更容易理解它。
假设您的数组中的一个字节是218
(无符号)。那是1101 1010
二进制的。
lo4
通过与位掩码对字节进行与运算来获得最低 4 位00001111
:
int lo4 = b & 0x0F;
这导致1010
,10
十进制。
hi4
通过与位掩码进行 AND 运算1111 0000
并向右移动 4 位来获得最高 4 位:
int hi4 = ( b & 0xF0 ) >> 4;
这导致1101
,13
十进制。
现在要获得这个字节的十六进制表示,您只需要将其转换为十六进制表示10
并13
连接。为此,您只需HEX_CHARS
在特定索引处查找准备好的字符串中的字符。10
-> A
,13
-> D
,导致218
-> DA
。
推荐阅读
- symfony - 是否需要为每个请求/响应更新 JWT 令牌中的 CSRF 令牌?
- html - 如何在背景图像url离子中连接动态图像路径
- html - 带主题的邮件形式,主题名称="XXXX"+输入
- python-3.x - 在 shapefile 的字段中查找最大值
- java - 使用其他存储库的文件运行 maven 测试
- javascript - 如何创建一个可以在一段代码中多次调用的等待函数
- angular - 不理解不可变对象
- javascript - 角度发送空参数。它不应该
- javascript - 为什么我可以多次声明一个 javascript var?
- amazon-web-services - DynamoDB 架构建议