---
title: "Encoding::UndefinedConversionError: \"\\xE5\" from ASCII-8BIT to UTF-8"
author: "RunUpwind"
date: "2011-07-21T11:59:41Z"
tags: []
categories: ["编程语言"]
slug: "encoding-undefinedconversionerror-xe5-from-ascii-8bit-to-utf-8"
draft: false
lastmod: "2011-08-02T13:51:29Z"
id: 1129605
url: "https://runupwind.iteye.com/blog/1129605"
---

在做编码转换时，遇了这个问题。原代码如下：

```
str.encode('UTF-8') if str.encoding != 'UTF-8'
```

所以就遇到了错误：Encoding::UndefinedConversionError: "\\xE5" from ASCII-8BIT to UTF-8

 

 

后来看了https://github.com/lassebunk/webcam\_app/issues/1

将代码修改为以下，

 

```
str.force_encoding('UTF-8') if str.encoding != 'UTF-8'
```

这只是改了字符串的encoding值，实际数据并未转码。

 

问题等待解决中...

 

 

2011-08-01问题解决 ，代码：

```
str = str.force_encoding('GBK')
str = str.encode('UTF-8')
```

 

思考：

当str.encoding == 'ASCII-8BIT'时，ruby并不知道这个str的编码。我用其他编辑器得知它的编码是GBK，所以我先强制将它标记为GBK，再转为UTF-8, 就成功了。