什么和& 0xff和MD5结构? [英] What does & 0xff do And MD5 Structure?

查看:186
本文介绍了什么和& 0xff和MD5结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class JavaMD5 {

    public static void main(String[] args) {
        String passwordToHash = "MyPassword123";
        String generatedPassword = null;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(passwordToHash.getBytes());
            byte[] bytes = md.digest();
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < bytes.length; i++) {
                sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1));
            }
            generatedPassword = sb.toString();

        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println(generatedPassword);
    }
}

这一行是问题所在:

sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1));

这个结构中每个部分做了什么????

what does each part do in this structure????

谢谢,我很抱歉要求Beacuse我是java新手。

Thanks and I'm sorry for asking Beacuse I'm new in java.

推荐答案

大概是代码很清楚,这里唯一的谜是这个表达式:

Presumably most of the code is clear and the only mystery for you here is this expression:

(bytes[i] & 0xff) + 0x100

第一部分:

bytes[i] & 0xff

将位置 i 的字节扩大为一个 int 值,位位置为8-31,零。在Java中, byte 数据类型是有符号整数值,因此扩展符号扩展了该值。没有& 0xff ,大于0x7f的值最终将为负 int 值。其余的是相当明显的:它增加了0x100,它只是打开索引8处的位(因为它保证在中为0(bytes [i]& 0xff)。然后通过调用 Integer.toString(...,16) String 值>。

widens the byte at position i to an int value with zeros in bit positions 8-31. In Java, the byte data type is a signed integer value, so the widening sign-extends the value. Without the & 0xff, values greater than 0x7f would end up as negative int values. The rest is then fairly obvious: it adds 0x100, which simply turns on the bit at index 8 (since it is guaranteed to be 0 in (bytes[i] & 0xff). It is then converted to a hex String value by the call to Integer.toString(..., 16).

首先添加0x100然后剥离1的原因(由子串(1)完成调用,从子行到第1位开始的子字符串)是为了保证最终结果中有两个十六进制数字。否则,低于0x10的字节值在转换为十六进制时最终会成为一个字符的字符串。

The reason for first adding 0x100 and then stripping off the 1 (done by the substring(1) call, which takes the substring starting at position 1 through the end) is to guarantee two hex digits in the end result. Otherwise, byte values below 0x10 would end up as one-character strings when converted to hex.

这是否具有更好的表现(当然不是更清晰)是否值得商榷:

It's debatable whether all that has better performance (it certainly isn't clearer) than:

sb.append(String.format("%02x", bytes[i]));

这篇关于什么和&amp; 0xff和MD5结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆