开发者

Byte array to string gives "???" [closed]

开发者 https://www.devze.com 2023-03-13 19:56 出处:网络
Closed. This question is not reproducible or was caused by typos.开发者_如何学运维 It is not currently accepting answers.
Closed. This question is not reproducible or was caused by typos.开发者_如何学运维 It is not currently accepting answers.

This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.

Closed 7 years ago.

Improve this question

So I am trying to write a steganography program in java.

Here is what I have so far (the important parts)

  private void hideMessage(){
    byte[] messageBytes = message.getBytes();
    //message is a string
    int messageLength = messageBytes.length;
    for(int i = messageLength-1; i>=0; i--){
      imageBytes[i+100000] = messageBytes[i];
      //imageBytes is a bitmap image read into a byte array using imageIO
    }
  }

and

  private void getMessage(){
    int messageLength = 11;
    byte[] messageBytes = new byte[messageLength];
    for(int i = messageLength; i>0; i--){
      messageBytes[i-1] = imageBytes[i+10000];
    }
    message = new String(messageBytes);
  }

However this is the output I get for the string:

???????????

What am I doing wrong?


Pay attention to your zeroes. Your comment says 1000, getMessage uses 10000, and hideMessage uses 100000

(reposted as answer since apparently that's all that was wrong)


You can't simply create a string from arbitrary bytes - the bytes must be encodings of characters in the encoding you are using (in your case, the default encoding). If you use bytes that don't map to a character, they will be mapped to '?'. The same is true in the other direction: If you have a string with characters which do not map to bytes, the getBytes() method will map them to (byte)'?'. I think one or both of this happened here.

If you are using JPG or a similar lossy image format, it will change the bytes of your image during saving.


If the plan is to actually change part of your bitmap bytes, you'd need to export the image as png, as its lossless. Jpeg would probably change the bytes slightly, which isn't a problem for an image, but for text its obviously critical.

Second, if you're going to pick 100,000 as a fixed position to insert the message, you should set that up as a constant to make it easier, and less error prone. Speaking of which, your current fixed offsets are off by a '0', 10,000 and 100,000.


But you should edit the raw file, but an instance of BufferedImage, then rewrite it back to a file with ImageIO.

0

精彩评论

暂无评论...
验证码 换一张
取 消